我有一個第三方服務返回JSON,其中一個字段包含數據集合。這是它返回的結構的一個例子。Unmarshal JSON可能是一個字符串或對象
{
"title": "Afghanistan",
"slug": "afghanistan",
"fields": {
"fieldOne": "",
"fieldTwo": {
"new1": {
"type": "contentBlock",,
"fields": {
"richTextBlick": "<p>This is the travel advice.<\/p>"
}
}
},
"fieldThree": {
"new1": {
"type": "introBlock",
"fields": {
"text": "This is a title"
"richText": "<p>This is the current travel summary for Afganistan.<\/p>"
}
},
"new2": {
"type": "contentBlock",
"fields": {
"richText": "<p>It has a second block of content!<\/p>"
}
}
},
"fieldfour": "country"
}
}
每個「字段」條目可以是字符串或其他對象。我想將它們解碼成類似下面的結構。
type EntryVersion struct {
Slug string `json:"slug"`
Fields map[string][]EntryVersionBlock `json:"fields"`
}
type EntryVersionBlock struct {
Type string `json:"type"`
Fields map[string]string `json:"fields"`
}
如果字段值只是一個字符串,我會敷在與「文本」,並在字段映射單個條目類型的EntryVersionBlock。
任何想法如何以有效的方式做到這一點?我可能必須在極端的情況下做幾百次。
感謝
嘗試使用這個庫https://github.com/tidwall/gjson – Radi