douzhi7070 2018-08-12 14:50
浏览 153
已采纳

构建golang结构以存储来自解析的JSON文件的数据

I'm trying to load a rather large JSON file that has x amount of JSON arrays. The issue I'm having is the fact that the each node in the data below has a unique name, so I'm not sure how to build the struct to store them.

Here is snippet of the data from the JSON file (This file can have many more nodes that just two below)

       {
            "timestamp": 1533397325,
            "total_nodes": 9522,
            "latest_height": 535196,
            "nodes": {
                "220.75.229.130:3927": [
                    70015,
                    "/Satoshi:0.13.2/",
                    1530858117,
                    13,
                    165277,
                    "220.75.229.130",
                    "Seoul",
                    "KR",
                    37.5985,
                    126.9783,
                    "Asia/Seoul",
                    "AS4766",
                    "Korea Telecom"
                ],
                "192.162.102.68:8333": [
                    70015,
                    "/Satoshi:0.15.1/",
                    1533061934,
                    13,
                    535196,
                    "192.162.102.68",
                    null,
                    "RU",
                    55.7386,
                    37.6068,
                    null,
                    "AS50113",
                    "MediaServicePlus LLC"
                ]        
          }
}

So far, this is my code, and JSON objects in Go:

type MyJsonName struct {
    LatestHeight int `json:"latest_height"`
    Timestamp    int `json:"timestamp"`
    TotalNodes   int `json:"total_nodes"`
    Nodes        struct {
        Data string
    } `json:"nodes"`
}

func main() {
    jsonFile, err := os.Open("someFile")
    if err != nil {
        fmt.Println(err)
    }
    byteValue, _ := ioutil.ReadAll(jsonFile)
    var MyJSONANE MyJsonName
    err = json.Unmarshal(byteValue, &MyJSONANE)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(MyJSONANE)
}

This code works great, my issue is the fact that Data in nodes in never populated with the JSON arrays and their contents.

This is the output: {535196 1533397325 9522 {}}

Any help adjusting my struct to read in the JSON arrays will be greatly appreciated. I would just like to draw emphasis to the names of the JSON arrays in nodes being unique, and there can be total_nodes amount of them.

  • 写回答

1条回答

  • dongmeng1875 2018-08-12 15:06
    关注

    Go for map[string]interface{} to store the nodes data. For unknown json data with dynamic keys Interfaces are best which will help you to store any type of data.

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type MyJsonName struct {
        LatestHeight int `json:"latest_height"`
        Timestamp    int `json:"timestamp"`
        TotalNodes   int `json:"total_nodes"`
        Nodes  map[string]interface{}
    }
    
    var byteValue string = `{
      "timestamp": 1533397325,
      "total_nodes": 9522,
      "latest_height": 535196,
      "nodes": {
        "220.75.229.130:3927": [
          70015,
          "/Satoshi:0.13.2/",
          1530858117,
          13,
          165277,
          "220.75.229.130",
          "Seoul",
          "KR",
          37.5985,
          126.9783,
          "Asia/Seoul",
          "AS4766",
          "Korea Telecom"
        ],
        "192.162.102.68:8333": [
          70015,
          "/Satoshi:0.15.1/",
          1533061934,
          13,
          535196,
          "192.162.102.68",
          null,
          "RU",
          55.7386,
          37.6068,
          null,
          "AS50113",
          "MediaServicePlus LLC"
        ]
      }
    }`
    
    func main() {
        var MyJSONANE MyJsonName
        err := json.Unmarshal([]byte(byteValue), &MyJSONANE)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Printf("%+v",MyJSONANE)
    }
    

    Working code on Go playground

    To fetch the underlying value from the interface{}, you require type assertion for each type. You can go for switch to get the value from interface recursively.

    func fetchValue(value interface{}) {
        switch value.(type) {
        case string:
            fmt.Printf("%v is an string 
     ", value.(string))
        case bool:
            fmt.Printf("%v is bool 
     ", value.(bool))
        case float64:
            fmt.Printf("%v is float64 
     ", value.(float64))
        case []interface{}:
            fmt.Printf("%v is a slice of interface 
     ", value)
            for _, v := range value.([]interface{}) {
                fetchValue(v)
            }
        case map[string]interface{}:
            fmt.Printf("%v is a map 
     ", value)
            for _, v := range value.(map[string]interface{}) {
                fetchValue(v)
            }
        default:
            fmt.Printf("%v is unknown 
     ", value)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。