简体   繁体   English

Go JSON 解析接口

[英]Go JSON parsing for interfaces

I have a json which is as follows:我有一个 json 如下:

{
  "parameters": {
    "key1": {
        "value": "someStringValue"
      },
    "key2": {
        "innerKey1": {
           "innerKey2": {
             "innerKey3": "someStringValue"
             },
          }
    }
    "key4": {
        "value": 123
    },
    "key5": {
        "value": true
    },
  }
}

As you can see I can have different kind of values (string, map, int, bool).如您所见,我可以有不同类型的值(字符串、map、int、bool)。 Following is the struct I've defined:以下是我定义的结构:

type TestStruct struct {
  Parameters map[string]ParameterValue 
}

type ParameterValue struct {
    Values map[string]interface{}
}

With this I'm facing issues when parsing the json, key1,key2,key3 are not being marshalled and their value is nil .有了这个,我在解析 json 时遇到了问题, key1,key2,key3没有被编组,它们的值为nil What should be the correct struct design for this?正确的结构设计应该是什么?

This seems to work fine:这似乎工作正常:

package main

import (
   "encoding/json"
   "fmt"
)

var s = `
{
   "parameters": {
      "key1": {"value": "someStringValue"},
      "key2": {
         "innerKey1": {
            "innerKey2": {"innerKey3": "someStringValue"}
         }
      },
      "key4": {"value": 123},
      "key5": {"value": true}
   }
}
`

func main() {
   var m struct {
      Parameters map[string]interface{}
   }
   json.Unmarshal([]byte(s), &m)
   fmt.Println(m.Parameters["key1"]) // map[value:someStringValue]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM