How do I parse a JSON string in Golang?

2019-06-06 02:38发布

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条回答
Luminary・发光体
2楼-- · 2019-06-06 03:08

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

查看更多
登录 后发表回答