dongmanni6916 2014-09-22 04:09
浏览 53
已采纳

去解组嵌套的JSON结构

Go Unmarshal nested JSON structure

http://play.golang.org/p/f6ilWnWTjm

I am trying to decode the following string but only getting null values.

How do I decode nested JSON structure in Go?

I want to convert the following to map data structure.

Please let me know.

package main

import (
  "encoding/json"
  "fmt"
)

func main() {
  jStr := `
{
    "AAA": {
        "assdfdff": ["asdf"],
        "fdsfa": ["1231", "123"]
    }
}
`
  type Container struct {
    Key string `json:"AAA"`
  }
  var cont Container

  json.Unmarshal([]byte(jStr), &cont)
  fmt.Println(cont)
}
  • 写回答

2条回答 默认 最新

  • doulidai6316 2014-09-22 04:36
    关注

    Use nested structs in Go to match the nested structure in JSON.

    Here's one example of how to handle your example JSON:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    func main() {
        jStr := `
        {
            "AAA": {
                "assdfdff": ["asdf"],
                "fdsfa": ["1231", "123"]
            }
        }
        `
    
        type Inner struct {
            Key2 []string `json:"assdfdff"`
            Key3 []string `json:"fdsfa"`
        }
        type Container struct {
            Key Inner `json:"AAA"`
        }
        var cont Container
        if err := json.Unmarshal([]byte(jStr), &cont); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%+v
    ", cont)
    }
    

    playground link

    You can also use an anonymous type for the inner struct:

    type Container struct {
        Key struct {
            Key2 []string `json:"assdfdff"`
            Key3 []string `json:"fdsfa"`
        }  `json:"AAA"`
    }
    

    playground link

    or both the outer and inner structs:

    var cont struct {
        Key struct {
            Key2 []string `json:"assdfdff"`
            Key3 []string `json:"fdsfa"`
        } `json:"AAA"`
    }
    

    playground link

    If you don't know the field names in the inner structure, then use a map:

    type Container struct {
        Key map[string][]string `json:"AAA"`
    }
    

    http://play.golang.org/p/gwugHlCPLK

    There are more options. Hopefully this gets you on the right track.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度