dougekui1518 2018-05-06 18:44
浏览 33

用go解析嵌套的JSON

I am trying to parse a nested json on GO ,

the json looks like this:

{
    "id"   : 12345656,
    "date" : "2018-05-02-18-16-17",
    "lists" : [
     {
          "empoyee_id": "12343",
          "name": "User1"

      },
      {
          "contractor_id" : "12343",
          "name":  "User1"
       }, 
       {
          "contractor_id" : "12343",
          "name":  "User1"
       }
    ]
}

My struct

type Result struct {
  id    int64    `json:"id"`
  Date  string   `json:"date"`
  Lists []string `json:"lists"`
}

I am trying to access it using the following:

var result Result
json.Unmarshal(contents, &result)

How can I change the above to access to the employee_id or the contractor_id fields ?

  • 写回答

1条回答 默认 最新

  • dsf6565 2018-05-06 21:31
    关注

    You need to use another type to store the nested data rather than a slice of strings like so:

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    var contents string = `{
        "id"   : 12345656,
        "date" : "2018-05-02-18-16-17",
        "lists" : [
         {
              "empoyee_id": "12343",
              "name": "User1"
    
          },
          {
              "contractor_id" : "12343",
              "name":  "User1"
           }, 
           {
              "contractor_id" : "12343",
              "name":  "User1"
           }
        ]
    }`
    
    type Result struct {
        ID    int64         `json:"id"`
        Date  string       `json:"date"`
        Lists []Contractor `json:"lists"`
    }
    
    type Contractor struct {
        ContractorID string `json:"contractor_id"`
        EmployeeID   string `json:"employee_id"`
        Name         string `json:"name"`
    }
    
    func main() {
        var result Result
        err := json.Unmarshal([]byte(contents), &result)
        if err != nil {
            panic(err)
        }
        fmt.Println(result)
    }
    

    Executable:

    https://play.golang.org/p/7dYArgz1V8y

    If you just want a single ID field on the nested object then you will need to do a custom unmarshal function on the result to work out which ID is present.

    评论

报告相同问题?

悬赏问题

  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow