I want to unmarshal a JSON object where one field contains a JSON string into one coherent object. How do I do that in Go?
Example:
Input:
{
"foo":1,
"bar":"{\"a\":\"Hello\"}"
}
Go type:
type Child struct {
A string `json:"a"`
}
type Main struct {
Foo int `json:"foo"`
Bar Child `json:"bar"`
}
I guess I’d need to implement a custom UnmarshalJSON
implementation on one of the types, but its twisting my head to figure out on which one and how.
2
Answers
I guess you want to treat this as if the JSON String were just part of the surrounding JSON object? If so, then yes, as you suggest, a custom
UnmarshalJSON
method onChild
should accomplish this.See it in the playground
if i were to create a custom
UnmarshalJson
for that data, I would create an auxiliary structauxMain
that has the same fields as the main struct but withBar
field as string. Then it unmarshals the JSON data into this auxiliary struct, extracting theFoo
field and theBar
field as a string. After that, it unmarshals the Bar field as string into theChild
struct, and assigns the extracted Foo field and the Child struct to the Main struct.It’s a round about way but seems to work in the playground.
try it out in the PlayGround and see: https://go.dev/play/p/wWIceUxu1tj
Don’t know if this is what you are looking for.