duanlei5339 2014-02-28 10:53
浏览 29
已采纳

如何在Go中解析JSON?

JSON

{
  "id" : "12387",
  "inv" :[
    {
      "qty" : 5,

       "seq" : 2,
       "invIs" : "1HG9876",
       "addCharges" :[
         {
          "amnt" : 24,
          "char" : "REI",
          "type" : "MT"
          },
          {
          "amnt" : 24,
          "char" : "REI",
          "type" : "MT"
          }
        ],

      "seq" : 3

    },
    {
      "qty" : 5,

       "seq" : 2,
       "invIs" : "1HG9876",
       "addCharges" :[
         {
          "amnt" : 24,
          "char" : "REI",
          "type" : "MT"
          },
          {
          "amnt" : 24,
          "char" : "REI",
          "type" : "MT"
          }
        ],

      "seq" : 3

    }
  ],
    "charges" : {
      "fee" : 24 ,
      "bkg" : 7676
    }

}

My JSON structure is like that shown above. I need to take amnt in inv-addCharges in an array. If it has ten elements in the array, I need to get that in an array containing the particular amnt alone in such a way like

[{"amnt" : 34 } ,{"amnt" : 34} .... so on ]

Things I tried:

var j map[string]interface{}
    err := json.Unmarshal([]byte(ticket), &j)
    if err != nil {
        panic(err)
    }

    // Pull out the parents object
    bytInv := j["inv"].([]interface{})    

    // // Print out mother and father
    fmt.Println(bytInv)

Output

[map[qty:5 seq:3 invIs:1HG9876 addCharges:[map[amnt:24 char:REI type:MT] map[amnt:24 char:REI type:MT]]] map[qty:5 seq:3 invIs:1HG9876 addCharges:[map[amnt:24 char:REI type:MT] map[amnt:24 char:REI type:MT]]]]

After this, I was not able to proceed any further.

Note: I don't want to use structs because I have many JSON structures for this. And that's my requirement given.

  • 写回答

1条回答 默认 最新

  • dow57588 2014-02-28 13:36
    关注

    Requirement or not, I really don't see why you insist on not using structs for this. Can you elaborate on exactly why this is the case?

    As evidenced by the example program below, the solution is so much easier to understand and reason about if you just represent the data as properly typed structs. You can run it on the Go playground to see it in action.

    There is one part of your JSON data which confuses me. Each Item node contains the seq field twice. Both with a different value. Which ever way you use to interpret the data, one of the fields will be lost. Depending on the implementation of the unmarshaller, it will either ignore the second field, or overwrite the first one with the second value. This is a bug in the way your data is generated.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "os"
    )
    
    func main() {
        charges, err := findCharges()
        if err != nil {
            fmt.Fprintf(os.Stderr, "%v
    ", err)
            os.Exit(1)
        }
    
        for _, c := range charges {
            fmt.Printf("%+v
    ", c)
        }
    }
    
    // findCharges locates all 'AddCharge` instances and returns them in a slice.
    func findCharges() ([]AddCharge, error) {
        var prod Product
    
        data := []byte(jsonString)
        err := json.Unmarshal(data, &prod)
        if err != nil {
            return nil, err
        }
    
        var charges []AddCharge
    
        for _, item := range prod.Items {
            charges = append(charges, item.AddCharges...)
        }
    
        return charges, nil
    }
    
    type Product struct {
        Id    string `json:"id"`
        Items []Item `json:"inv"`
    }
    
    type Item struct {
        Quantity   int         `json:"qty"`
        Sequence   int         `json:"seq"`
        Inventory  string      `json:"invIs"`
        AddCharges []AddCharge `json:"addCharges"`
        Charges    []Charge    `json:"charges"`
    }
    
    type Charge struct {
        Fee int `json:"fee"`
        Bkg int `json:"bkg"`
    }
    
    type AddCharge struct {
        Amount int    `json:"amnt"`
        Char   string `json:"char"`
        Type   string `json:"type"`
    }
    
    const jsonString = `{
      "id" : "12387",
      "inv" :[
        {
          "qty" : 5,
           "seq" : 2,
           "invIs" : "1HG9876",
           "addCharges" :[
             {
              "amnt" : 24,
              "char" : "REI",
              "type" : "MT"
              },
              {
              "amnt" : 12,
              "char" : "REI",
              "type" : "MT"
              }
            ],
    
          "seq" : 3
    
        },
        {
          "qty" : 5,
    
           "seq" : 2,
           "invIs" : "1HG9876",
           "addCharges" :[
             {
              "amnt" : 64,
              "char" : "REI",
              "type" : "MT"
              },
              {
              "amnt" : 36,
              "char" : "REI",
              "type" : "MT"
              }
            ],
    
          "seq" : 3
    
        }
      ],
        "charges" : {
          "fee" : 24 ,
          "bkg" : 7676
        }
    
    }`
    

    edit: If the addCharges data is really all you are interested in, you can omit all the fields you do not need from the structs. The unmarshaller will simply ignore the data for which the struct has no field defined.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败