I'm reading a json and want to get the label field with a specific id. What I currently have is:
with open("local_en.json") as json_file:
parsed_dict = json.load(json_file)
print(parsed_dict) # works
print(parsed_dict["interface"]) # works
print(parsed_dict["interface"]["testkey"])
My json has data blocks (being "interface" or "settings") and those data blocks contain arrays.
{
"interface":[
{"id": "testkey", "label": "The interface block local worked!"}
{"id": "testkey2", "label": "The interface block local worked, AGAIN!"}
],
"settings":[
],
"popup_success":[
],
"popup_error":[
],
"popup_warning":[
],
"other_strings":[
]
}
CodePudding user response:
You need to browse through all the values and check if it matches expected value. Because values are not guaranteed to be unique in a dictionary, you can't simply refer to them directly like you do with keys.
print([el for el in d["interface"] if "testkey" in el.values()])
CodePudding user response:
You can "find" the element in the interface
list via a list-comprehension, and fetch the label from that element. For instance:
label = [x['label'] for x in parsed_dict['interface'] if x['id'] == 'testkey'][0]
If you cannot assume that the relevant id exists, then you can wrap this in a try-except, or you can get a list of the labels and validate that it isn't of length 0, or whatever you think would work best for you.
key = 'testkey'
labels = [x['label'] for x in parsed_dict['interface'] if x['id'] == key]
assert len(labels) > 0, f"There's no matching element for key {key}"
label = labels[0] # Takes the first if there are multiple such elements in the interface array
And while you're at it, you might want to explicitly deal with there being multiple elements with the same id, etc.
Clarification regarding your error(s):
parsed_dict["interface"]
is a list, so you can index it with int
s (and slices and stuff, but that's besides the point), and not with str
ings.
Each of the list elements is a dict
, with two key
s: id
and label
, so even if you were to take a specific element, say -
el = parsed_dict["interface"][0]
you still couldn't do el['testkey']
, because that's a value
of the dict, not a key
.
You could check if the id
is the one you're looking for though, via -
if el['id'] == 'testkey':
print('Yup, this is it')
label = el['label']
In fact, the single line I gave above is really just shorthand for running over all the elements with a loop and doing just that...