Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
moshevi opened this issue Nov 28, 2018 · 5 comments
Closed

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

moshevi opened this issue Nov 28, 2018 · 5 comments

Comments

@moshevi
Copy link

moshevi commented Nov 28, 2018

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
Copy link
Collaborator

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
Copy link
Author

moshevi commented Nov 28, 2018

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

@generikvault
Copy link
Collaborator

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
Copy link
Author

moshevi commented Nov 28, 2018

Thanks @generikvault

@moshevi
Copy link
Author

moshevi commented Nov 28, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants