gjson icon indicating copy to clipboard operation
gjson copied to clipboard

How to get all matches with Paths

Open keminar opened this issue 5 months ago • 1 comments

code

package main

import (
	"fmt"

	"github.com/tidwall/gjson"
)

func main() {
	ret := []byte(`{
		"result": {
			"data": [
				{"data": [{"type": "quan", "value": 1}, {"type": "quan", "value": 2}, {"type": "quan", "value": 3},  {"type": "other", "value": 4}]},
				{"data": [{"type": "quan", "value": 3}]}
			]
		}
	}`)

	path := "result.data.#.data.#(type==\"quan\")"
	result := gjson.GetBytes(ret, path)
	fmt.Println(result, result.Paths(string(ret)))

	path = "result.data.#.data.#(type==\"quan\")#"
	result = gjson.GetBytes(ret, path)
	fmt.Println(result, result.Paths(string(ret)))

}

output

[{"type": "quan", "value": 1},{"type": "quan", "value": 3}] [result.data.0.data.0 result.data.1.data.0] [[{"type": "quan", "value": 1},{"type": "quan", "value": 2},{"type": "quan", "value": 3}],[{"type": "quan", "value": 3}]] [ ]

keminar avatar Jul 15 '25 03:07 keminar

I want to get

[[{"type": "quan", "value": 1},{"type": "quan", "value": 2},{"type": "quan", "value": 3}],[{"type": "quan", "value": 3}]]

 [result.data.0.data.0 result.data.0.data.1 result.data.0.data.2 result.data.1.data.0]

Looks like there is a similar issue: https://github.com/tidwall/gjson/issues/267

keminar avatar Jul 15 '25 03:07 keminar