Parse JSON Path

I need to parse a JSON path in a format similar to how it is done with the JSON functions in MSSQL. However I don’t really want to add the external library jsonpath-ng to make it happen. I know that GSON is used quite frequently, and with all of perspective being stored in JSON, is this something that a built in function already covers?

Example:

I have JSON

{
  "level1":
  {
    "level2":{
      "finalKey": "value"
    }
  },
  "otherKey":"someValue"
}

And I need to get the value for $.level1.level2.finalKey to equal “value”

My guess/hope is that there is a function that executes the jsonGet expression that I could potentially leverage to extrapolate this.

Probably the closest first-party would be JsonUtilities.read - but you’ll probably have to do some type coercion from your original JSON (probably raw Python dicts?) to the GSON-based classes we use internally.

Put together:

from com.inductiveautomation.ignition.common import TypeUtilities, JsonUtilities

d = {
  "level1":
  {
    "level2":{
      "finalKey": "value"
    }
  },
  "otherKey":"someValue"
}

def get(json, path):
	gson = TypeUtilities.pyToGson(json)
	return JsonUtilities.read(gson, path).orElse(None)
	
print get(d, "level1.level2.finalKey")
1 Like

You are the best Paul! This is perfect.

Another note, incase you wanted this to be all in python for testing purposes. You could use reduce as well to solve this, I just realized this after going through Pauls example.

from functools import reduce
import operator

def find(element, json):
    return reduce(operator.getitem, element.split('.'), json)
    
d = {
  "level1":
  {
    "level2":{
      "finalKey": "value"
    }
  },
  "otherKey":"someValue"
}

print find("level1.level2.finalKey", d)
1 Like

That will limit you to object keys without allowing array addressing, though. You could split the difference and just use JsonPath.parse() and then extract the elements.