【问题标题】:parsing nested JSON with go用 go 解析嵌套的 JSON
【发布时间】:2018-05-06 18:44:19
【问题描述】:

我正在尝试解析 GO 上的嵌套 json,

json 看起来像这样:

{
    "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 []string `json:"lists"`
}

我正在尝试使用以下方式访问它:

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

如何更改以上内容以访问employee_id 或contractor_id 字段?

【问题讨论】:

  • 您的代码无效。请粘贴您的实际工作代码。关注this guide 制作一个最小、完整、可验证的示例,以便我们为您提供帮助。
  • 而且 JSON 也不是有效的 JSON。
  • 我编辑了问题,很抱歉代码不好,我是新手

标签: go


【解决方案1】:

您需要使用另一种类型来存储嵌套数据,而不是像这样的字符串切片:

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

可执行文件:

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

如果您只想要嵌套对象上的单个 ID 字段,那么您需要对结果执行自定义解组函数来确定存在哪个 ID。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    相关资源
    最近更新 更多