From e91a88bec4cc8ee8e36401714522db8759a407a6 Mon Sep 17 00:00:00 2001 From: tidwall Date: Fri, 28 Jun 2019 04:41:32 -0700 Subject: [PATCH] Allow for chaining syntax in multi array --- gjson.go | 20 +++++++++++++++--- gjson_test.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 3 deletions(-) diff --git a/gjson.go b/gjson.go index 46b3029..ffc611b 100644 --- a/gjson.go +++ b/gjson.go @@ -1270,6 +1270,12 @@ func parseArray(c *parseContext, i int, path string) (int, bool) { res := Get(val, rp.query.path) if queryMatches(&rp, res) { if rp.more { + left, right, ok := splitPossiblePipe(rp.path) + if ok { + rp.path = left + c.pipe = right + c.piped = true + } res = Get(val, rp.path) } else { res = Result{Raw: val, Type: JSON} @@ -1277,10 +1283,18 @@ func parseArray(c *parseContext, i int, path string) (int, bool) { if rp.query.all { if len(multires) == 0 { multires = append(multires, '[') - } else { - multires = append(multires, ',') } - multires = append(multires, res.Raw...) + + raw := res.Raw + if len(raw) == 0 { + raw = res.String() + } + if raw != "" { + if len(multires) > 1 { + multires = append(multires, ',') + } + multires = append(multires, raw...) + } } else { c.value = res return i, true diff --git a/gjson_test.go b/gjson_test.go index 9a62a17..4e50e90 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -1704,3 +1704,60 @@ func TestDeepSelectors(t *testing.T) { t.Fatalf("expected '%v', got '%v'", "Murphy", res) } } + +func TestMultiArrayEx(t *testing.T) { + json := `{ + "info": { + "friends": [ + { + "first": "Dale", "last": "Murphy", "kind": "Person", + "cust1": true, + "extra": [10,20,30], + "details": { + "city": "Tempe", + "state": "Arizona" + } + }, + { + "first": "Roger", "last": "Craig", "kind": "Person", + "cust2": false, + "extra": [40,50,60], + "details": { + "city": "Phoenix", + "state": "Arizona" + } + } + ] + } + }` + + var res string + + res = Get(json, `info.friends.#[kind="Person"]#.kind|0`).String() + if res != "Person" { + t.Fatalf("expected '%v', got '%v'", "Person", res) + } + res = Get(json, `info.friends.#.kind|0`).String() + if res != "Person" { + t.Fatalf("expected '%v', got '%v'", "Person", res) + } + + res = Get(json, `info.friends.#[kind="Person"]#.kind`).String() + if res != `["Person","Person"]` { + t.Fatalf("expected '%v', got '%v'", `["Person","Person"]`, res) + } + res = Get(json, `info.friends.#.kind`).String() + if res != `["Person","Person"]` { + t.Fatalf("expected '%v', got '%v'", `["Person","Person"]`, res) + } + + res = Get(json, `info.friends.#[kind="Person"]#|kind`).String() + if res != `` { + t.Fatalf("expected '%v', got '%v'", ``, res) + } + res = Get(json, `info.friends.#|kind`).String() + if res != `` { + t.Fatalf("expected '%v', got '%v'", ``, res) + } + +}