ojg icon indicating copy to clipboard operation
ojg copied to clipboard

Getting full path of a rule in the json

Open LironKS opened this issue 2 years ago • 2 comments

Hi, Thank you for this contribution, it's very helpful :)

I'm looking for a method that for a given rule is returning a list of the full paths it appears in the json. For example, my json is: { "name": "John Smith", "male": true, "age": 35, "address": "New York", "null": null, "metadata": { "date": "2022-04-01T00:00:00.000Z", "count": "5", "name": "John Smith" }, "test": { "name": "John Smith" } }

and the rule is: "$.*.name"

So I want to have something like this: ["$.metadata.name","$.test.name"]

Is there any method that does this?

Thanks.

LironKS avatar Feb 01 '23 11:02 LironKS

There is not at this point in time.

This relates to #59

ohler55 avatar Feb 03 '23 02:02 ohler55

Does the jp Locate() function do what you were looking for?

ohler55 avatar Feb 02 '24 19:02 ohler55

It does.

package main

import (
	"fmt"
	"github.com/ohler55/ojg/jp"
	"github.com/ohler55/ojg/oj"
)

func main() {
	jsonDataString := `{
		"name": "John Smith",
		"male": true,
		"age": 35,
		"address": "New York",
		"null": null,
		"metadata": {
			"date": "2022-04-01T00:00:00.000Z",
			"count": "5",
			"name": "John Smith"
		},
		"test": {
			"name": "John Smith"
		}
	}`
	data, _ := oj.ParseString(jsonDataString)

	myJP := jp.MustParseString(`$.*.name`)
	myLoc := myJP.Locate(data, 0)
	fmt.Printf("%+v\n", myLoc)
}

Output

[$.metadata.name $.test.name]

Run on playgroud

Skeeve avatar Feb 27 '24 20:02 Skeeve