0

I'd like to extract an elememt by "$". But it retrieves nothing (the 1st call of main.py). Does anybody know what is wrong? Thanks.

$ cat data.json
{
  "id": {
    "$": {
      "view": "all",
      "id": "sec4",
      "role": "materials-methods"
    }
  }
}

$ cat main.py 
#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import sys
import json
json_data = json.load(sys.stdin)
import jsonpath_rw_ext
res = jsonpath_rw_ext.match(sys.argv[1], json_data)
for match in res:
    print match.keys()

$ < data.json ./main.py '$."$"'
$ < data.json ./main.py '$."id"'
[u'$']
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
user1424739
  • 11,937
  • 17
  • 63
  • 152
  • I hope you agree with my edit. It makes it simpler to create the test setup than using a here-doc (which couldn't be copy/pasted because of the `> ` in front). If you disagree, feel free to roll it back. Why do you use Python2? – hek2mgl Aug 13 '19 at 23:53
  • Looks fine. I just have been using python 2 for all my code. It takes time to change. – user1424739 Aug 13 '19 at 23:55

2 Answers2

0

The right jsonpath expression to use would be '$.id.$'.

Note: Please don't use Python2 for new code and migrate existing Python2 code to Python3

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I don't want to specify `id`. I want to search for any nodes of `$`, which does not have to be a child of `id`. – user1424739 Aug 14 '19 at 01:01
  • The expressions says: Return all child nodes from `$`. – hek2mgl Aug 14 '19 at 07:03
  • I think the jsonpath expression should be `$.."$"`. BTW, I'd like to and I'd like to add the restriction that there is a "role" field with the value "materials-methods", and I'd like to get the parent of the node found. How to do it? – user1424739 Aug 14 '19 at 10:34
  • Ok, you want to extract information from an element `$`, regardless of it's position in the tree. Your question doesn't say that. To summarize it, you want to retrieve the parent node of a role node which's value is xyz, regardless of it's position in the tree. Is that what you want? – hek2mgl Aug 14 '19 at 10:43
  • Not precisely. I'd like to retrieve the parent of a node who has a field "role" with a value "xyz". The position of the node in the tree does not matter. – user1424739 Aug 14 '19 at 10:48
0

Try this one

$[?(!@.$)]

This ignores all the nodes containing $

kaushik
  • 556
  • 1
  • 7
  • 22