[Solved] How to parse JSON extract array [closed]


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.

something like this

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)
}

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

I used this JSON

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

solved How to parse JSON extract array [closed]