2 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是一個(gè)非常簡(jiǎn)短的示例,說(shuō)明如何快速輕松地執(zhí)行此操作。步驟是; 解組到通用map[string]interface{}然后,假設(shè)沒(méi)有錯(cuò)誤,只編組你想要的內(nèi)部對(duì)象。
var temp := &map[string]interface{}
if err := json.Unmarshal(input, temp); err != nil {
return err;
}
return json.Marshal(temp["response"])

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
我編寫了一個(gè)包μjson來(lái)做到這一點(diǎn):在 JSON 文檔上執(zhí)行通用轉(zhuǎn)換而不解組它們。
input := []byte(`
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"q": "solo",
"wt": "json"
}
},
"response": {
"numFound": 2,
"start": 0,
"docs": [
{ "name": "foo" },
{ "name": "bar" }
]
}
}`)
blacklistFields := [][]byte{
[]byte(`"responseHeader"`), // note the quotes
}
b := make([]byte, 0, 1024)
err := ujson.Walk(input, func(_ int, key, value []byte) bool {
for _, blacklist := range blacklistFields {
if bytes.Equal(key, blacklist) {
// remove the key and value from the output
return false
}
}
// write to output
if len(b) != 0 && ujson.ShouldAddComma(value, b[len(b)-1]) {
b = append(b, ',')
}
if len(key) > 0 {
b = append(b, key...)
b = append(b, ':')
}
b = append(b, value...)
return true
})
if err != nil {
panic(err)
}
fmt.Printf("%s", b)
// Output: {"response":{"numFound":2,"start":0,"docs":[{"name":"foo"},{"name":"bar"}]}}
您可以在博客文章中閱讀更多相關(guān)信息。我把答案放在這里以防其他人可能需要它。
- 2 回答
- 0 關(guān)注
- 220 瀏覽
添加回答
舉報(bào)