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 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作