Skip to content

Commit

Permalink
Allow for Index > 0 on path compontent that are not modifiers.
Browse files Browse the repository at this point in the history
This commit fixes an issue where non-modifier path components
such as '@hello' return 0 for the Result.Index value.
  • Loading branch information
tidwall committed Aug 5, 2022
1 parent 980f12c commit 475b403
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
25 changes: 20 additions & 5 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ func parseArrayPath(path string) (r arrayPathResult) {
}
if path[i] == '.' {
r.part = path[:i]
if !r.arrch && i < len(path)-1 && isDotPiperChar(path[i+1]) {
if !r.arrch && i < len(path)-1 && isDotPiperChar(path[i+1:]) {
r.pipe = path[i+1:]
r.piped = true
} else {
Expand Down Expand Up @@ -936,8 +936,23 @@ right:
}

// peek at the next byte and see if it's a '@', '[', or '{'.
func isDotPiperChar(c byte) bool {
return !DisableModifiers && (c == '@' || c == '[' || c == '{')
func isDotPiperChar(s string) bool {
if DisableModifiers {
return false
}
c := s[0]
if c == '@' {
// check that the next component is *not* a modifier.
i := 1
for ; i < len(s); i++ {
if s[i] == '.' || s[i] == '|' {
break
}
}
_, ok := modifiers[s[1:i]]
return ok
}
return c == '[' || c == '{'
}

type objectPathResult struct {
Expand All @@ -959,7 +974,7 @@ func parseObjectPath(path string) (r objectPathResult) {
}
if path[i] == '.' {
r.part = path[:i]
if i < len(path)-1 && isDotPiperChar(path[i+1]) {
if i < len(path)-1 && isDotPiperChar(path[i+1:]) {
r.pipe = path[i+1:]
r.piped = true
} else {
Expand Down Expand Up @@ -989,7 +1004,7 @@ func parseObjectPath(path string) (r objectPathResult) {
continue
} else if path[i] == '.' {
r.part = string(epart)
if i < len(path)-1 && isDotPiperChar(path[i+1]) {
if i < len(path)-1 && isDotPiperChar(path[i+1:]) {
r.pipe = path[i+1:]
r.piped = true
} else {
Expand Down
11 changes: 11 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2543,3 +2543,14 @@ func TestJSONString(t *testing.T) {
testJSONString(t, string(buf[:]))
}
}

func TestIndexAtSymbol(t *testing.T) {
json := `{
"@context": {
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"@vocab": "http://schema.org/",
"sh": "http://www.w3.org/ns/shacl#"
}
}`
assert(t, Get(json, "@context.@vocab").Index == 85)
}

0 comments on commit 475b403

Please sign in to comment.