tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.2k stars 846 forks source link

forEach fo current json string #338

Closed baxiry closed 10 months ago

baxiry commented 10 months ago

I can't use ForEach via json fields. Because it's not gjson.Result type. Currently I use this trick to convert Json string to Resulte type.

data := `{"a": 1, "b": 2}`
result := gjson.Get(`{"obj":`+data+`}`, "obj")
result.ForEach(func(k, v gjson.Result) bool {
       // ...
       return true 
 })

I'm looking for a better way to get the same result. any idea ? thank you

tidwall commented 10 months ago

Use the gjson.Parse function which converts a JSON string to a gjson.Result.

obj := `{"a": 1, "b": 2}`
gjson.Parse(obj).ForEach(func(k, v gjson.Result) bool {
        // ...
        return true 
})
tidwall commented 10 months ago

Optionally you can use @this

obj := `{"a": 1, "b": 2}`
result := gjson.Get(obj, "@this")
result.ForEach(func(k, v gjson.Result) bool {
            // ...
            return true 
})
baxiry commented 10 months ago

Wow! so thanks @tidwall

tidwall commented 10 months ago

You're welcome.