Closed cahernao closed 3 years ago
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
}
https://www.json.cn
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]