Search code examples
jsonstringgomarshalling

Is it possible to add a nested json "as is" in Go?


Is this possible way to add nested json "as is". The nested json doesn't have any structure and might be different. I need to put the nested json data directly to the root node.

https://play.golang.org/p/MzBt7DLQEpD

type RootJson struct {
    NestedJson []byte
    AdditionalField string
}

func main() {
    nestedJson := []byte("{\"number\": 1, \"string\": \"string\", \"float\": 6.56}")

    rootJson := RootJson{nestedJson, "additionalField"}
    payload, _ := json.Marshal(&rootJson)

    fmt.Println(string(payload))

}

Solution

  • Yes, it's possible. Use the json.RawMessage type which implements custom marshaling / unmarshaling, which "renders" it as-is into the JSON output. It's just a plain byte slice:

    type RawMessage []byte
    

    Its value should be the UTF-8 encoded byte sequence of the raw JSON text (exactly what you get when you do a conversion, e.g. []byte("someText")).

    type RootJson struct {
        NestedJson      json.RawMessage
        AdditionalField string
    }
    

    With this, the output will be (try it on the Go Playground):

    {"NestedJson":{"number":1,"string":"string","float":6.56},
        "AdditionalField":"additionalField"}
    

    (Indentation added by me.)