doucang2831 2015-01-18 18:03
浏览 159

如何在Golang中解析JSON字符串?

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条回答 默认 最新

  • duanlei4759 2015-01-18 18:11
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题