Compare commits

..

No commits in common. "6ee9f877d683381343bc998c137339c7ae908b86" and "1ff915dd81b03cb807d30dff5ac085bd12d433be" have entirely different histories.

3 changed files with 18 additions and 35 deletions

View File

@ -427,6 +427,16 @@ if result.Index > 0 {
This is a best-effort no allocation sub slice of the original json. This method utilizes the `result.Index` field, which is the position of the raw data in the original json. It's possible that the value of `result.Index` equals zero, in which case the `result.Raw` is converted to a `[]byte`.
## Get multiple values at once
The `GetMany` function can be used to get multiple values at the same time.
```go
results := gjson.GetMany(json, "name.first", "name.last", "age")
```
The return value is a `[]Result`, which will always contain exactly the same number of items as the input paths.
## Performance
Benchmarks of GJSON alongside [encoding/json](https://golang.org/pkg/encoding/json/),

View File

@ -3410,7 +3410,7 @@ func (t Result) Path(json string) string {
if !rcomp.Exists() {
goto fail
}
comp := Escape(rcomp.String())
comp := escapeComp(rcomp.String())
path = append(path, '.')
path = append(path, comp...)
}
@ -3425,31 +3425,17 @@ fail:
// isSafePathKeyChar returns true if the input character is safe for not
// needing escaping.
func isSafePathKeyChar(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c <= ' ' || c > '~' || c == '_' ||
c == '-' || c == ':'
return c <= ' ' || c > '~' || c == '_' || c == '-' || c == ':' ||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')
}
// Escape returns an escaped path component.
//
// json := `{
// "user":{
// "first.name": "Janet",
// "last.name": "Prichard"
// }
// }`
// user := gjson.Get(json, "user")
// println(user.Get(gjson.Escape("first.name"))
// println(user.Get(gjson.Escape("last.name"))
// // Output:
// // Janet
// // Prichard
func Escape(comp string) string {
// escapeComp escaped a path compontent, making it safe for generating a
// path for later use.
func escapeComp(comp string) string {
for i := 0; i < len(comp); i++ {
if !isSafePathKeyChar(comp[i]) {
ncomp := make([]byte, len(comp)+1)
copy(ncomp, comp[:i])
ncomp = ncomp[:i]
ncomp := []byte(comp[:i])
for ; i < len(comp); i++ {
if !isSafePathKeyChar(comp[i]) {
ncomp = append(ncomp, '\\')

View File

@ -2701,16 +2701,3 @@ func TestModDig(t *testing.T) {
assert(t, Get(json, "@dig:name").String() == `["melinda","jake"]`)
assert(t, Get(json, "@dig:secret").String() == `["password"]`)
}
func TestEscape(t *testing.T) {
json := `{
"user":{
"first.name": "Janet",
"last.name": "Prichard"
}
}`
user := Get(json, "user")
assert(t, user.Get(Escape("first.name")).String() == "Janet")
assert(t, user.Get(Escape("last.name")).String() == "Prichard")
assert(t, user.Get("first.name").String() == "")
}