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"]]
1
  • 1
    Instead of trying to directly access the map from key to values diirectly, you probably mean to use Request.FormValue instead. golang.org/pkg/net/http/#Request.FormValue Commented Jan 19, 2015 at 0:12

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 (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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.