I have an example of json as below:
{"key1": "val1", "key2": "val2", "key3": [{"k1": v1"}, {"k2": "v2"}]}
Now I need to split it into two objects:
{"key1": "val1", "key2": "val2", "key3": {"k1": v1"}}
and {"key1": "val1", "key2": "val2", "key3": {"k2": v2"}}
Basically I want to split the key3 elements keeping all other keys same in the new structure.
My structure is as below:
type myType struct {
key1 string
key2 string
key3 []interface{}
}
Please let me know how I can achieve that.
With regards, -M-
There is one minor issue with your struct: The properties have to be exported so that values can be unmarshalled into a struct. In addition you have to tag the properties.
If you want to split an instance of myType
according to its values in Key3
, you have to do it manually.
Below is working example:
package main
import (
"encoding/json"
"fmt"
)
var bytes = []byte(`{"key1": "val1", "key2": "val2", "key3": [{"k1": "v1"}, {"k2": "v2"}]}`)
type myType struct {
Key1 string `json:"key1"`
Key2 string `json:"key2"`
Key3 []interface{} `json:"key3"`
}
func (mt myType) Split() []myType {
res := make([]myType, len(mt.Key3))
for i, k3 := range mt.Key3 {
res[i] = myType{Key1: mt.Key1, Key2: mt.Key2, Key3: []interface{}{k3}}
}
return res
}
func main() {
t := &myType{}
err := json.Unmarshal(bytes, t)
if err != nil {
panic(err)
}
fmt.Printf("%+v
", t.Split())
}