-1

I have a json which is as follows:

{
  "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). 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. What should be the correct struct design for this ?

tortuga
  • 737
  • 2
  • 13
  • 34
  • 1
    Show your complete minimal code that demonstrates the problem. – zerkms Mar 22 '21 at 23:35
  • 1
    use https://golang.org/pkg/encoding/json/#RawMessage for dynamic data. Deeper in your code you can decode to correct type based on the current context. – Dmitry Harnitski Mar 22 '21 at 23:40
  • Are "key1", "key2", ..., etc known at compile time or are the keys dynamic? – Charlie Tumahai Mar 22 '21 at 23:48
  • @CeriseLimón they are not known at compile time and are dynamic – tortuga Mar 22 '21 at 23:51
  • If they are not known at compile time you will need to unmarshal into an `interface{}`. See this answer for a full explanation of why @steven's answer works https://stackoverflow.com/questions/40559250/golang-dynamically-creating-member-of-struct – Christian Mar 23 '21 at 07:37

1 Answers1

2

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]
}
Zombo
  • 1
  • 62
  • 391
  • 407