PaesslerAG / jsonpath

BSD 3-Clause "New" or "Revised" License
172 stars 37 forks source link

Is there a way to get the path from the fetch #10

Closed moshevi closed 5 years ago

moshevi commented 5 years ago

If I look at { "a": { "b": { "c": 1, "d": 2 } } }

and running this expression '$..c' I will get the value 1. Is there a way to get c full path as well (like '$a.b.c') ?

generikvault commented 5 years ago

Hi moshevi,

in this package is an extension for placeholders. This isn't official json path anymore but it helps to access the keys.

The path {#: $..x} will return a map[string]interface{} from jsonpath to value. In this case $["a"]["b"]["c"]

moshevi commented 5 years ago

Hi @generikvault Can you send me a code sample for that? Thanks.

generikvault commented 5 years ago

The placeholder # without a number is a hack and it works only for the wildcard parts so you have to add the c manually:

` builder := jsonpath.PlaceholderExtension()

path, err := builder.NewEvaluable(`{#: $..c}`)
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}

v := interface{}(nil)
err = json.Unmarshal([]byte(`{ "a": { "b": { "c": 1, "d": 2 } } }`), &v)

if err != nil {
    fmt.Println(err)
    os.Exit(1)
}

devices, err := path(context.Background(), v)
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}

for device, name := range devices.(map[string]interface{}) {
    fmt.Printf("%s -> %v\n", device, name)
}

// Unordered output:
// $["a"]["b"] -> 1`

Actually palceholders should be used like #0 or #1 to access the nth key or in case of .. an array of the keys. (see the gval example in godoc)

moshevi commented 5 years ago

Thanks @generikvault

moshevi commented 5 years ago

@generikvault Is there any samples for using regex for jsonpath or gval?