douguwo2275 2018-03-19 12:10
浏览 52
已采纳

如何解组未知字段名称的JSON以构造[重复]

This question already has an answer here:

Is it possible to unmarshal JSON with unknown field? That field name is always different, but the structure is the same. JSON is a result of POST request.

My code:

package main

import "fmt"
import "encoding/json"

var body = []byte(`{
    "unknown_field": {
            "known_field_1": [[1,2,3,4,5],[10,20,30,40,50],[100,200,300,400,500]],
            "known_field_2": [[11,21,31,41,51]],
            "known_field_3": [[12,22,32,42,52],[14,44,34,44,54]]
        }
}`)

type MyStruct struct {
    MainData map[string]mData `json:"-"`
}

type mData struct {
    knownField1 [][5]int `json:"known_field_1"`
    knownField2 [][5]int `json:"known_field_2"`
    knownField3 [][5]int `json:"known_field_3"`
}

func NewMyStruct() MyStruct {
    ms := MyStruct{}
    ms.MainData = make(map[string]mData)
    return ms
}

func main() {
    myStruct := NewMyStruct()
    if err := json.Unmarshal(body, &myStruct); err != nil {
        panic(err)
    }

    fmt.Println(myStruct) // gives {map[]}
}
</div>
  • 写回答

1条回答 默认 最新

  • douqiang5933 2018-03-19 12:16
    关注

    Simply use a map if you don't know the key, and the value type of the map may be the struct describing the structure:

    type mData struct {
        KnownField1 [][5]int `json:"known_field_1"`
        KnownField2 [][5]int `json:"known_field_2"`
        KnownField3 [][5]int `json:"known_field_3"`
    }
    

    Note that you must export the fields for this to work!

    And the unmarshaling code:

    var data map[string]mData
    if err := json.Unmarshal(body, &data); err != nil {
        panic(err)
    }
    
    fmt.Println(data)
    for k, v := range data {
        fmt.Println(k, v)
    }
    

    Output (try it on the Go Playground):

    map[unknown_field:{[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}]
    unknown_field {[[1 2 3 4 5] [10 20 30 40 50] [100 200 300 400 500]] [[11 21 31 41 51]] [[12 22 32 42 52] [14 44 34 44 54]]}
    

    See related questions:

    How to parse/deserlize a dynamic JSON in Golang

    Unmarshal JSON with unknown fields

    Unmarshal json string to a struct that have one element of the struct itself

    JSON Nested dynamic structures Go decoding

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

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加