From 256887a8aad21f227053cbd1136842ac9e93d5c8 Mon Sep 17 00:00:00 2001 From: Josh Baker Date: Tue, 28 Mar 2017 17:04:10 -0700 Subject: [PATCH] Fix for invalid matching on prefixed key Thanks to @Poorva17 for finding this issue. Fixes #20 --- gjson.go | 3 +++ gjson_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/gjson.go b/gjson.go index 9b28df2..69be577 100644 --- a/gjson.go +++ b/gjson.go @@ -1765,6 +1765,9 @@ next_key: goto match_not_atend } } + if len(paths[j]) > len(key) { + goto nomatch + } // matched and at the end of the path goto match_atend } diff --git a/gjson_test.go b/gjson_test.go index 99b5048..f8fa2d3 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -576,6 +576,32 @@ func TestManyBasic(t *testing.T) { testMany(true, `[world]`, strings.Repeat("a.", 70)+"hello") } +const sampleJSON = `{ "name": "FirstName", "name1": "FirstName1", "address": "address1", "addressDetails": "address2", }` + +func TestIssue20(t *testing.T) { + expectedValues := []string{"FirstName", "FirstName1", "address1", "address2"} + paths := []string{"name", "name1", "address", "addressDetails"} + var result []Result + for i := 0; i < 2; i++ { + var which string + if i == 0 { + which = "Get" + result = nil + for j := 0; j < len(expectedValues); j++ { + result = append(result, Get(sampleJSON, paths[j])) + } + } else if i == 1 { + which = "GetMany" + result = GetMany(sampleJSON, paths...) + } + for j := 0; j < len(expectedValues); j++ { + if result[j].String() != expectedValues[j] { + t.Fatalf("expected '%v', got '%v' for '%s'", expectedValues[j], result[j].String(), which) + } + } + } +} + func TestRandomMany(t *testing.T) { var lstr string defer func() {