tidwall / gjson

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

Hope to get the entire JSON with `gjson.Get()` #239

Closed Tyxiang closed 2 years ago

Tyxiang commented 2 years ago

such as

package main
import "github.com/tidwall/gjson"
const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
func main() {
    value := gjson.Get(json, ".")
    println(value.String())
}

result

{"name":{"first":"Janet","last":"Prichard"},"age":47}
tidwall commented 2 years ago

The path that is provided to a Get operation typically works on objects and arrays. The dot is just a separator of path components.

For the json {"name":{"first":"Janet","last":"Prichard"},"age":47}

The path name.last is two components, "name" and "last", and will return "Prichard"

Now for the json {"":{"first":"Janet","":"Prichard"},"age":47}

The path . is also two components, "" and "", and will also return "Prichard"

This behavior is by design.

Fortunately there's the handy modifier @this that was added in #150, which allows for:

@this               => {"name":{"first":"Janet","last":"Prichard"},"age":47}
@this.name          => {"first":"Janet","last":"Prichard"}
@this.name.last     => "Prichard"
Tyxiang commented 2 years ago

The path that is provided to a Get operation typically works on objects and arrays. The dot is just a separator of path components.

For the json {"name":{"first":"Janet","last":"Prichard"},"age":47}

The path name.last is two components, "name" and "last", and will return "Prichard"

Now for the json {"":{"first":"Janet","":"Prichard"},"age":47}

The path . is also two components, "" and "", and will also return "Prichard"

This behavior is by design.

Fortunately there's the handy modifier @this that was added in #150, which allows for:

@this               => {"name":{"first":"Janet","last":"Prichard"},"age":47}
@this.name          => {"first":"Janet","last":"Prichard"}
@this.name.last     => "Prichard"

Great solution! Thank you for your reply, I didn't read it carefully enough. I like your work, thank you very much.