在Go中解析动态json

在Go中解析动态json

问题描述:

I am trying to parse the following json structure, where the fields marked with "val1" and "val2" are constantly changing, so I cannot use a predefined struct. How could I parse this json in a way to be able to loop through every single "val"? Thank you!

 {"result":true,"info":{"funds":{"borrow":{"val1":"0","val2":"0"},"free":{"val1":"0","val2":"0"},"freezed":{"val1":"0","val2":"0"}}}}

我正在尝试解析以下json结构,其中标有“ val1”和“ val2”的字段不断 变化,所以我不能使用预定义的结构。 我如何解析这种json,以便能够遍历每个“ val”? 谢谢! p>

  {“结果”:true,“信息”:{“资金”:{“借款”:{“ val1”:“ 0”,“ val2”  : “0”}, “免费”:{ “VAL1”: “0”, “val2的”: “0”}, “冻结”:{ “VAL1”: “0”, “val2的”: “0”}}  }} 
  code>  pre> 
  div>

By unmarshalling into the following struct I can loop through the desired fields.

type Fields struct {
Result bool `json:"result"`
Info   struct {
    Funds struct {
        Borrow, Free, Freezed map[string]interface{}
    } `json:"funds"`
} `json:"info"`
}

package main

import (
    "fmt"
    "encoding/json"
)

type Root struct {
    Result bool `json:"result"`
    Info   Info `json:"info"`
}

type Info struct {
    Funds struct {
        Borrow, Free, Freezed map[string]interface{}
    } `json:"funds"`
}

func main() {
    var rootObject Root
    jsonContent := " {\"result\":true,\"info\":{\"funds\":{\"borrow\":{\"val1\":\"0\",\"val2\":\"0\"},\"free\":{\"val1\":\"0\",\"val2\":\"0\"},\"freezed\":{\"val1\":\"0\",\"val2\":\"0\"}}}}"

    if err := json.Unmarshal([]byte(jsonContent), &rootObject); err != nil {
        panic(err)
    }
    fmt.Println(rootObject)
}