首页 > 文章列表 > 使用golang访问json数据

使用golang访问json数据

188 2024-02-05
问题内容

我有以下 json 文档:

{
  id: int
  transaction_id: string
  total: string
  line_items: [
    {
      id: int
      name: string
    }

  ]  
}

这是我的代码

type Order struct {
    ID            int           `json:"id"`
    TransactionId string        `json:"transaction_id"`
    Total         string        `json:"total"`
    LineItems     []interface{} `json:"line_items"`
}

...
var order Order
json.Unmarshal([]byte(sbody), &order)

for index, a := range order.LineItems {

        fmt.Println(a["name"])
}

我收到错误:

in无效操作:无法索引(接口{}类型的变量)

我应该创建一个 item 结构吗?


正确答案


修改lineitems字段类型为[]map[string]interface{}

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    type Order struct {
        ID            int                      `json:"id"`
        TransactionId string                   `json:"transaction_id"`
        Total         string                   `json:"total"`
        LineItems     []map[string]interface{} `json:"line_items"`
    }

    var order Order
    err := json.Unmarshal([]byte(`{
        "id": 1,
        "transaction_id": "2",
        "total": "3",
        "line_items": [
            {
                "id": 2,
                "name": "444"
            }
        ]
    }`), &order)
    if err != nil {
        panic(err)
    }

    for _, a := range order.LineItems {
        fmt.Println(a["name"])
    }
}