将 JSON 与数组转换

我编写了以下代码来从 JSON 获取数组,并且想要检索类似的内容

[{“id”:“id1”,“友好”:“友好1”},{“id”:“id2”,“友好”:“友好2”}]

但它是空的:

[{"id":"","friend":""},{"id":"","friend":""}]

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))

}


慕村9548890
浏览 97回答 1
1回答

子衿沉夜

尝试创建另一个结构体,其中有一个名为Sourcetype 的字段source。在下面的示例中,我将此称为 struct 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))}```
打开App,查看更多内容
随时随地看视频慕课网APP