I have the following JSON response:
[
{
"talent_id": "b520ad50-5302-45ce-9121-5ff42d67b4fb",
"platform": "facebook",
"posts": [
{
"insights": [
{
"name": "post_impressions_organic_unique",
"values": [
{
"value": 1828
}
]
},
{
"name": "post_stories_by_action_type",
"values": [
{
"like": 42
}
]
}
],
"type": "photo",
"post_id": "24225267232_10154099759037233"
},
{
"insights": [
{
"name": "post_impressions_organic_unique",
"values": [
{
"value": 864
}
]
},
{
"name": "post_stories_by_action_type",
"values": [
{
"like": 19
}
]
}
],
"type": "photo",
"post_id": "24225267232_10154099756677233"
}
]
}
]
I need to restructure/flatten it into something like this:
{
"talent_id": "b520ad50-5302-45ce-9121-5ff42d67b4fb",
"platform": "facebook",
"posts": [{
"post_id": "24225267232_10154051404062233",
"type": "photo",
"organic_impressions_unique": 8288,
"post_story_actions_by_type": {
"shares": 234,
"comments": 838,
"likes": 8768
}
}, {
"post_id": "24225267232_10154051404062233",
"type": "photo",
"organic_impressions_unique": 8288,
"post_story_actions_by_type": {
"shares": 234,
"comments": 838,
"likes": 8768
}
}]
}
I am using a struct to map the JSON response:
type JsonData struct {
TalentID string `json:"talent_id"`
Platform string `json:"platform"`
Posts []struct {
PostID string `json:"post_id"`
Type string `json:"type"`
Insights []struct {
//Data []map[string]interface{}
Name string `json:"name"`
} `json:"insights"`
} `json:"posts"`
}
My problem is with the data inside the posts and how can I map it, I am using a map to fill the data and Marshal it to generate the new structure of JSON.
Here is my code:
messages := [] JsonData{}
json.Unmarshal(body, &messages)
m := make(map[string]interface{})
m["talent_id"] = messages[0].TalentID
m["platform"] = messages[0].Platform
for _, p := range messages[0].Posts {
for _, i := range p.Insights {
// here is where I got lost and couldn't know how to fill the data inside the posts
}
}
jsonString, err := json.Marshal(m)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(jsonString))
P.S. the metrics post_impressions_organic_unique and post_stories_by_action_type are not static, they can change or other keys might be returned here