如何解析JSON提取数组

人气:525 发布:2022-10-16 标签: json go

问题描述

我与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"
        }
    ]
}

611