My input json data is this (cannot be changed, from an external resource):
[{
"Url": "test.url",
"Name": "testname"
},{
"FormName": "Test - 2018",
"FormNumber": 43,
"FormSlug": "test-2018"
}]
I have two structs that will always match the data within the array:
type UrlData struct{
"Url" string `json:Url`
"Name" string `json:Name`
}
type FormData struct{
"FormName" string `json:FormName`
"FormNumber" string `json:FormNumber`
"FormSlug" string `json:FormSlug`
}
Obviously the code below will not work, but is it possible at the top level (or otherwise) to declare something like this:
type ParallelData [
urlData UrlData
formData FormData
]
I think Answer of Peter is awesome.
Option 1:
if you need above structure then you can define it as
In this case, your json will look like
Option 2:
You've provide following json:
If your json really look like, then you can use following
struct
For both options, you can Unmarshall your json like this
See option 1 in playground
See option 2 in playground
Use a two step process for unmarshaling. First, unmarshal a list of arbitrary JSON, then unmarshal the first and second element of that list into their respective types.
You can implement that logic in a method called UnmarshalJSON, thus implementing the json.Unmarshaler interface. This will give you the compound type you are looking for:
Try it on the playground: https://play.golang.org/p/QMn_rbJj-P-
You can unmarshal into a
map[string]interface{}
for example:Output:
Playground