我已经编写了以下代码来从JSON获取数组,并希望检索类似
[{{id“:” id1“,” friendly“:” friendly1“},{” id“:” id2“,” friendly“:” friendly2“}}
但它是空的:
[{“id”:“”,“友好”:“”},{“id”:“”,“友好”:“”}]
package main
import (
"encoding/json"
"fmt"
)
var input = `[
{
"not needed": "",
"_source": {
"id": "id1",
"friendly": "friendly1"
}
},
{
"_source": {
"id": "id2",
"friendly": "friendly2"
}
}]`
type source struct {
Id string `json:"id"`
Friendly string `json:"friendly"`
}
func main() {
result := make([]source, 0)
sources := []source{}
json.Unmarshal([]byte(input), &sources)
for _, n := range sources {
result = append(result, n)
}
out, _ := json.Marshal(result)
fmt.Println(string(out))
}
最佳答案
尝试创建另一个结构,该结构具有一个称为Source
类型的source
的字段。在下面的示例中,我将此结构称为outer
。您的输入应该是outer
数组,结果应该是source
数组。
像这样:
import (
"encoding/json"
"fmt"
)
var input = `[
{
"not needed": "",
"_source": {
"id": "id1",
"friendly": "friendly1"
}
},
{
"_source": {
"id": "id2",
"friendly": "friendly2"
}
}]`
type outer struct {
Source source `json:"_source"`
}
type source struct {
Id string `json:"id"`
Friendly string `json:"friendly"`
}
func main() {
result := make([]source, 0)
sources := []outer{}
json.Unmarshal([]byte(input), &sources)
for _, n := range sources {
result = append(result, n.Source)
}
out, _ := json.Marshal(result)
fmt.Println(string(out))
}```
关于json - 使用数组转换JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60660215/