json - 使用数组转换JSON

标签 json go

我已经编写了以下代码来从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/

相关文章:

Go Mod Private Repo导入路径(找不到模块)

go - 并发性:限制 goroutines 没有按预期工作

java - Jackson:无法使用嵌套 DTO 处理托管/反向引用 'defaultReference'

json - 在 Logstash 中解析 JSON 对象数组

jquery - 错误: jQuery . ..未被调用——Ajax从Node.js跨域服务器请求geoJSON

docker - 导入路径不是以主机名开头

mysql - Rails with mysql "Unknown type ' json' for column 'special_info' "

json - 将扁平 json 转换为嵌套 json

mongodb - UpdateOne 因 E11000 重复键错误而失败

go - 如何在 Go 中将包分配给变量?