【问题标题】:How to parse JSON extract array [closed]如何解析 JSON 提取数组
【发布时间】:2018-10-08 10:50:21
【问题描述】:

我使用 Go。

我想解析一个 JSON 文件。但我只需要 JSON 文件中的一个数组,而不是所有结构。

这是 JSON 文件:link

我只需要items的数组。

如何从 JSON 中提取这个数组?

【问题讨论】:

  • 请求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作的总结,以及您在解决问题时遇到的困难的描述。
  • 这似乎是一件容易的事,但我不确定你到底想要什么。也许是一个澄清的例子

标签: json go


【解决方案1】:

这取决于你的结构的定义。如果您只想要项目数组,则应解组主结构,然后获取项目数组。

类似的东西

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type Structure struct {
    Items []Item `json:"items"`
}
type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    data, err := ioutil.ReadFile("myjson.json")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    structure := new(Structure)
    json.Unmarshal(data, structure)
    theArray := structure.Items
    fmt.Println(theArray)
}

Unmarshal 将忽略您在结构中未定义的字段。所以这意味着你应该只添加你想要解组的内容

我使用了这个 JSON

{
    "total_count": 123123,
    "items": [
        {
            "id": 1,
            "name": "name1"
        },
        {
            "id": 2,
            "name": "name2"
        }
    ]
}

【讨论】:

    猜你喜欢
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    相关资源
    最近更新 更多