dsg7513 2017-11-26 15:49
浏览 426
已采纳

使用Golang go-simplejson遍历Json

I am working in Golang,and using the package github.com/bitly/go-simplejson

I will receive a Json from the client side, I already constructed the json object using that package. Now I need to iterate over all the "first level" elements of that Json. The Json is something like this:

{"Name":"demo2","Creator":"some creator","URL":"www.url.com","GACode":"UA-xxxx"} 

My code is:

body, _ := ioutil.ReadAll(req.Body)
settings,_ := simplejson.NewJson(body)
fmt.Printf("
Json: %+v",settings)

for k, v := range settings.MustArray() {
    fmt.Println("
 k:",k)
    fmt.Println("
 v:",v)
}

When I print the Json I receive:

Json: &{data:map[Name:demo2 Creator:some creator URL:www.url.com GACode:UA-xxxx]}

And the loop is giving me nothing, MustArray() is giving me an empty array. The keys of that Json are very dynamic so I cannot do somehting like .Get("TheKey") because I don't know the name of the keys that can come in the json.

Then, how can I loop over that Json? I am more insterested in loop over the first level of that Json.

  • 写回答

1条回答 默认 最新

  • dougua4836 2017-11-26 16:17
    关注

    In Go you can use the range loop to iterate over a map the same way you would over an array or slice. The values provided to you by the range loop on each iteration will be the map's keys and their corresponding values.

    So you can simply change your loop line from:

    for k, v := range settings.MustArray() {
    

    To:

    for k, v := range settings.MustMap() {
    

    Also, personally, I would recommend ditching simplejson unless you have a better use case for it than what you have in your example. Using the standard encoding/json you can achieve the same result with less effort in my opinion.

    var settings map[string]interface{}
    if err := json.NewDecoder(req.Body).Decode(&settings); err != nil {
        panic(err)
    }
    fmt.Printf("
    Json: %+v",settings)
    
    for k, v := range settings {
        fmt.Println("
     k:",k)
        fmt.Println("
     v:",v)
    }
    

    Example on playground: https://play.golang.org/p/TKdO5pOJCY

    More info on for with range here: https://golang.org/ref/spec#For_range

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上