From f92dbfc6b20e4af58d3fd0a32ac0338277012ddb Mon Sep 17 00:00:00 2001 From: Josh Baker Date: Mon, 30 Jul 2018 14:44:31 -0700 Subject: [PATCH] Fix different reuslts on duplicate keys fixes #79 --- gjson.go | 8 ++++++-- gjson_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/gjson.go b/gjson.go index c08c87a..1da1552 100644 --- a/gjson.go +++ b/gjson.go @@ -383,9 +383,13 @@ func (t Result) arrayOrMap(vc byte, valueize bool) (r arrayOrMapResult) { key = value } else { if valueize { - r.oi[key.Str] = value.Value() + if _, ok := r.oi[key.Str]; !ok { + r.oi[key.Str] = value.Value() + } } else { - r.o[key.Str] = value + if _, ok := r.o[key.Str]; !ok { + r.o[key.Str] = value + } } } count++ diff --git a/gjson_test.go b/gjson_test.go index 17af327..867fae6 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -1391,3 +1391,18 @@ func TestNumFloatString(t *testing.T) { t.Fatalf("expected '%v', got '%v'", "-9007199254740993", res.String()) } } + +func TestDuplicateKeys(t *testing.T) { + // this is vaild json according to the JSON spec + var json = `{"name": "Alex","name": "Peter"}` + if Parse(json).Get("name").String() != + Parse(json).Map()["name"].String() { + t.Fatalf("expected '%v', got '%v'", + Parse(json).Get("name").String(), + Parse(json).Map()["name"].String(), + ) + } + if !Valid(json) { + t.Fatal("should be valid") + } +}