1

Given a URL like the following.

http://127.0.0.1:3001/find?field=hostname&field=App&filters=["hostname":"example.com,"type":"vm"]

How do I extract JSON values corresponding to keys for eg: hostname 'example.com' and type 'vm'.

I am trying

filters := r.URL.Query()["filters"]

which gives following output:

[["hostname":"example.com,"type":"vm"]]
Kasinath Kottukkal
  • 2,471
  • 4
  • 22
  • 28
  • 1
    Instead of trying to directly access the map from key to values diirectly, you probably mean to use `Request.FormValue` instead. http://golang.org/pkg/net/http/#Request.FormValue – dyoo Jan 19 '15 at 00:12

1 Answers1

4

Use the encoding/json package to parse JSON. The query string in the example URL does not contain valid JSON.

Here's an example show how to use the JSON parser on a slightly different URL.

s := `http://127.0.0.1:3001/find?field=hostname&field=App&filters={"hostname":"example.com","type":"vm"}`
u, err := url.Parse(s)
if err != nil {
    log.Fatal(err)
}
var v map[string]string
err = json.Unmarshal([]byte(u.Query().Get("filters")), &v)
if err != nil {
    log.Fatal(err)
}
fmt.Println(v)

playground example

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • 1
    The example "string" the question presents isn't even a string, technically. By using `r.URL.Query()`, they have a value of type `map[string][]string` (http://golang.org/pkg/net/url/#Values). So what the question is presenting isn't technically accurate: they're should be getting back a list with a single string. They probably did a simple `fmt.Println(filters)` on the value, rather than an output statement that presents more literal output, such as `fmt.Printf("%#v\n", filters)`. – dyoo Jan 19 '15 at 00:16