Paebbels
Paebbels

Reputation: 16229

jsonpath_rw for Python: How to navigate relatively?

I have a configuration database stored in a json file. This file is read from disk, parsed by Pythons json library and stored in a variable called json.

Now I'm investigating jsonpath_rw to build more readable path expressions then writing pure Python code to access multiple nested dicts and arrays.

Here is my current code:

# select all UART device serial numbers
exprSerial = parse('FPGAList.[*].UART.Serial')

#for serial in UART serial list
for match in exprSerial.find(json):
  print("Match: " + match.value + "    Path:" + str(match.full_path))

  if (match.value == USBSerial):
    #exprUART = match.full_path.Descendants) #under construction

The first expression lists all UART device serial numbers. The result is displayed on screen and working. Regarding the online documentation, I can print out the full path of the matching object by accessing match.full_path. This is a jsonpath object. If I call str(..) on it, it's transformed into a readable string.

Next, my code compares the value with a given serial number. If it's true, I would like to check some other parameters for safety: e.g. USBDeviceVendor. This key is also stored in the json file on the same hierarchy level.

My goal is it to construct a new jsonpath relative to match.full_path to access USBDeviceVendor.

Bad solution: exprVendor = parse(str(match.full_path) + "..USBDeviceVendor")

Is it possible to extend match.full_path like match.full_path.relative("..USBDeviceVendor")?

Upvotes: 2

Views: 1293

Answers (1)

Dan D.
Dan D.

Reputation: 74655

If you want to go up one level and then back down. Rather than look for the matching descendants of the current result.

Use `parent`:

parse('`parent`.USBDeviceVendor').find(match)

Consider:

>>> import jsonpath_rw as jp
>>> obj = {'y':{'x':1,'g':{'t':0}}}
>>> jp.parse('`parent`.g').find(jp.parse("y.x").find(obj)[0])[0].value
{'t': 0}

Otherwise:

parse("`this`..USBDeviceVendor").find(match)

Consider:

>>> import jsonpath_rw as jp
>>> obj = {'y':{'x':{'g':{'t':0}}}}
>>> jp.parse("`this`..t").find(jp.parse("y.x").find(obj)[0])[0].value
0

Upvotes: 2

Related Questions