How to convert a deeply nested part of json into a single string with Go

206 views Asked by At

I have some json data that has a structure similar to the following:

{
     "value1": "some value"
     "value2": "some other value"
     "value3": "another value"
     "value4": {
          "data":[
              {
                ...more nested values here with a few more levels
               }
             ]
            }
}

How would I lay out the struct so that all the data for "value4" comes back as a single string with Go?

Currently I'm using json.NewDecoder(r.Body).Decode(dataValues) where dataValues is a struct similar to:

type DataValues struct {
Value1 string `json:"value1"`
Value2 string `json:"value2"`
Value3 string `json:"value3"`
// not sure how to define Value4
}

Thanks in advance!

1

There are 1 answers

0
hoenir On BEST ANSWER

How would I lay out the struct so that all the data for "value4" comes back as a single string with Go?

If you want you can "delay" the unmarshaling and capture the part that you want to treat as a string by using RawMessage from encoding/json.

Here is a simple solution.