Save reference to a python dictionary (from a json file) item in a variable

Viewed 188

I'm trying to save the reference to a value in a json file where item orders could not be guaranteed. So far, what I have for a dataset like this one:

"Values": [
  {
    "Object": "DFC_Asset_05",
    "Properties": [
      {
        "Property": "WeightKilograms",
        "Value Offset": 5
      },
      {
        "Property": "WeightPounds",
        "Value Offset": 10
      }
    ]
  },
  {
    "Object": "DFC_Asset_05",
    "Properties": [
      {
        "Property": "Name",
        "Value Offset": 25
      },
      {
        "Property": "ShortName",
        "Value Offset": 119
      }
    ]
  }
]

and retrieving this object:

{
  "Property": "ShortName",
  "Value Offset": 119
}

Is a string like this:

reference = "[Object=DFC_Asset_06][Properties][Property=Name]"

Which looks nice and understandable in a string, but it's very unclean to find the referenced value as I must first parse the reference it with a regex then loop in the data to retrieve the matching item.

Am I doing this wrong? Is there a better way to do this? I looked at the reduce() function however it seems like it's made for dictionaries with static data. For example, I could not save the direct keys:

reference = "[1][Properties][1]"
reference_using_reduce = [1, "Properties", 1]

As they might not always be in that order

1 Answers

You can run "queries" on JSONs without referencing specific indexes using the pyjq module:

query = (
    '.Values[]'  # On all the items in "Values"
    '|select(."Object" == "DFC_Asset_06")'  # Find key "Object" which holds this value
    '|."Properties"[]'  # And get all the items of "Properties"
    '|select(."Property" == "Name")'  # Where the key "Property" holds the value "Name" 
)
pyjq.first(query, d)

Result:

{'Property': 'Name', 'Value Offset': 25}

You can read more about jq in the documentations.

Related