ohler55 / ojg

Optimized JSON for Go
MIT License
839 stars 50 forks source link

Getting full path of a rule in the json #111

Closed LironKS closed 4 months ago

LironKS commented 1 year ago

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.

ohler55 commented 1 year ago

There is not at this point in time.

This relates to #59

ohler55 commented 7 months ago

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

Skeeve commented 6 months ago

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