我有以下JSON響應:重組的Json使用Golang
[
{
"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"`
}
我的問題是與帖子裏面的數據,我如何映射它,我正在使用地圖f虐待數據並將其編組以生成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不是一成不變的,他們可以改變或其他鍵可能在這裏
你爲什麼不簡單地在struct對象上運行一個元帥?這將工作,因爲你提供了符文,它會正確地將其轉換爲JSON。 – ishaan
它不會工作,因爲我不知道'Insights []結構體' –
裏面會填充什麼是的,所以只需在結構體中定義一個'[] map [string]接口''。它會自行處理所有事情。讓它像'Insights [] map [string] interface {}' – ishaan