0

I have a struct as follows:

type Node struct {
    Name     string
    Children []*Node
    Values   []string
}

I also have a set of json files describing my trees such as:

{
  "something": {
    "someblah": [
      "fluf",
      "glah"
    ],
    "someother": {
      "someotter": [
        "blib",
        "fnar"
      ]
    }
  }
}

How can I deserialize these files into the structs?

All the examples I found seem to require a different structure with named key/value pairs.

For this, the structure is key:

  • the key is the struct name
  • the map contents are children
  • the lists contents are values

I cannot understand how to map this logic into the golang json serializer.

1
  • why not unmarshal into map[string]interface{}? Commented Mar 23, 2019 at 22:45

1 Answer 1

4

The easiest approach is to decode to map[string]interface{} and convert that to the desired structure:

var m map[string]interface{}
err := json.Unmarshal(data, &m)
if err != nil {
    // handle error
}
node := convert(m, "")

...

func convert(name string, m map[string]interface{}) *Node {
    n := Node{Name: name}
    for k, v := range m {
        switch v := v.(type) {
        case []interface{}:
            nn := Node{Name: k}
            for _, e := range v {
                s, ok := e.(string)
                if !ok {
                    panic(fmt.Sprintf("expected string, got %T", e))
                }
                nn.Values = append(nn.Values, s)
            }
            n.Children = append(n.Children, &nn)
        case map[string]interface{}:
            n.Children = append(n.Children, convert(k, v))
        default:
            panic("unexpected type")
        }
    }
    return &n
}

The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.

Run it on the playground.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this helped me find the correct solution. However, there seems to be a bug in the example: In the values case, there is no node created and the values are attached to the parent. In the example, each node has either children or values.
@Wilbert See updated answer. It would have been helpful if the question showed an example of the expected result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.