dongyo1818 2016-12-28 18:19
浏览 95
已采纳

如何使用Golang解组动态json对象

let me start by telling that I'm pretty recent in the Go world.

What I'm trying to do is to read the json I get from a JSON API (I don't control). Everything is working fine, I can show the received ID and Tags too. But the fields field is a little bit different, because its a dynamic array.

I can receive from the api this:

{
    "id":"M7DHM98AD2-32E3223F",
    "tags": [
        {
            "id":"9M23X2Z0",
            "name":"History"
        },
        {
            "id":"123123123",
            "name":"Theory"
        }
    ],
    "fields": {
        "title":"Title of the item",
        "description":"Description of the item"
    }
}

Or instead of title and description I could receive only description, or receive another random object like long_title. The objects return may differ completly and can be an infinite possibility of objects. But it always returns objects with a key and a string content like in the example.

This is my code so far:

type Item struct {
    ID string `json:"id"`
    Tags []Tag `json:"tags"`
    //Fields []Field `json:"fields"`
}

// Tag data from the call
type Tag struct {
    ID string `json:"id"`
    Name string `json:"name"`
}

// AllEntries gets all entries from the session
func AllEntries() {
    resp, _ := client.Get(APIURL)
    body, _ := ioutil.ReadAll(resp.Body)

    item := new(Item)
    _ = json.Unmarshal(body, &item)

    fmt.Println(i, "->", item.ID)
}

So the Item.Fields is dynamic, there is no way to predict what will be the key names, and therefore as far I can tell, there is no way to create a struct for it. But again, I'm pretty newbie with Go, could someone give me any tips? Thanks

  • 写回答

1条回答 默认 最新

  • duanfei9278 2016-12-28 18:46
    关注

    If the data in "fields" is always going to be a flat-dict then you can use map[string]string as type for the Fields.


    For arbitrary data specify Fields as a RawMessage type and parse it later on based on its content. Example from docs: https://play.golang.org/p/IR1_O87SHv

    If the fields are way too unpredictable then you can keep this field as is([]byte) or if there are fields that are always going to common then you can parse those and leave the rest(but this would result in loss of data present in other fields).

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

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存