如何解析JSON提取数组 [英] How to parse JSON extract array

查看:375
本文介绍了如何解析JSON提取数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Go合作.

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

I would like to parse a JSON file. But I only need just one array from the JSON file, not all the structure.

这是JSON文件:链接

我只需要items的数组.

如何从JSON中仅提取此数组?

How can I extract just this array from the JSON?

推荐答案

这取决于您的结构定义.如果只需要项数组,则应先解组主体结构,然后获取项数组.

That depends of the definition of your structs. if you want only the array of items, you should unmarshal the main structure and then get the items array.

类似的东西

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将忽略您尚未在结构中定义的字段.所以这意味着您只应添加您想解组的内容

The Unmarshal will ignore the fields you don't have defined in your struct. so that means you should add only what you whant to unmarshal

我使用了这个JSON

I used this JSON

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

这篇关于如何解析JSON提取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆