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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?