为了账号安全,请及时绑定邮箱和手机立即绑定

将 JSON 与数组转换

将 JSON 与数组转换

Go
慕村9548890 2023-08-14 17:45:37
我编写了以下代码来从 JSON 获取数组,并且想要检索类似的内容[{“id”:“id1”,“友好”:“友好1”},{“id”:“id2”,“友好”:“友好2”}]但它是空的:[{"id":"","friend":""},{"id":"","friend":""}]package mainimport (    "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))}
查看完整描述

1 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

尝试创建另一个结构体,其中有一个名为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))

}```


查看完整回答
反对 回复 2023-08-14
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信