我有以下JSON响应:
[
{
"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"
}
]
}
]
我需要将其重组/展平为这样的东西:
{
"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
}
}]
}
我正在使用结构来映射 JSON 响应:
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"`
}
我的问题是帖子中的数据以及如何映射它,我正在使用地图来填充数据并封送它以生成 JSON 的新结构。
这是我的代码:
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))
附言post_impressions_organic_unique和post_stories_by_action_type指标不是静态的,它们可以更改或在此处返回其他键
保持结构为:
type NameValue struct {
Name string `json:"name"`
Values []map[string]interface{} `json:"values"`
}
type JsonData struct {
TalentID string `json:"talent_id"`
Platform string `json:"platform"`
Posts []struct {
PostID string `json:"post_id"`
Type string `json:"type"`
Insights []NameValue `json:"insights"`
} `json:"posts"`
}
创建另一个类似于下面的结构:
type JsonDataRes struct {
TalentID string `json:"talent_id"`
Platform string `json:"platform"`
Posts []map[string]interface{} `json:"posts"`
}
在JsonData
结构中拥有数据后,循环访问见解对象,并手动为新的JsonDataRes
对象以及帖子[]map[string]interface{}
中的PostId
和Type
值分配值