tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.12k stars 847 forks source link

Help with array #204

Closed cahernao closed 3 years ago

cahernao commented 3 years ago

I have an array but with diferent name, so How I can get that name and the array?

Example

{ "Departamentos": [{ "Deportes": [{ "Nombre": "Aurora" }, { "Nombre": "Amador" }, { "Nombre": "Armados" } ] }, { "Comida": [{ "Nombre": "A comer todo", }] }, { "Celulares": [] } ]

}

So I searching something like that:

value :=gjson.Get(json, "SomethingLOL") and value= [Deportes, Comida, Celulares]

aihanjiao commented 3 years ago

if you only using github.com/tidwall/gjson in golang:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/tidwall/gjson"
)

var str = `{
"Departamentos": [{
"Deportes": [{
"Nombre": "Aurora"
},
{
"Nombre": "Amador"
},
{
"Nombre": "Armados"
}
]
},
{
"Comida": [{
"Nombre": "A comer todo",
}]
},
{
"Celulares": []
}
]

}`

func main() {
    var keys []string
    t := gjson.Parse(str)
    for _, v := range t.Get("Departamentos").Array() {
        keys = append(keys, getKeys(v.Map())...)
    }
    fmt.Println(keys)
    /*
    [Deportes Comida Celulares]
    */

    // if you want get xx["key"] = value
    data := map[string]interface{}{}
    for _, v := range t.Get("Departamentos").Array() {
        for _, k := range getKeys(v.Map()) {
            data[k] = v.Map()[k].Value()
        }
    }
    fmt.Println(data) // map
    /*
    map[Celulares:[] Comida:[map[Nombre:A comer todo]] Deportes:[map[Nombre:Aurora] map[Nombre:Amador] map[Nombre:Armados]]]
    */
    // and then
    fmt.Println(data["Comida"])
    /*
    [map[Nombre:A comer todo]]
    ===
    [{"Nombre":"A comer todo"}]
    */
    dJson, _ := json.Marshal(data)
    fmt.Println(string(dJson)) // json map
    /*
    {"Celulares":[],"Comida":[{"Nombre":"A comer todo"}],"Deportes":[{"Nombre":"Aurora"},{"Nombre":"Amador"},{"Nombre":"Armados"}]}
    */
}

func getKeys(m map[string]gjson.Result) []string {
    j := 0
    keys := make([]string, len(m))
    for k := range m {
        keys[j] = k
        j++
    }
    return keys
}

should be confirmed json data what does it look like at first

enter your json data into the website https://www.json.cn

截屏2021-05-02 01 18 07