dsg7513
2017-11-26 15:49 阅读 264

使用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 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

    点赞 评论 复制链接分享

相关推荐