I am using python
and have the following JSON block, json_player
, which is stored as a list:
[
{
"id": "name",
"value": "john"
},
{
"id": "sport",
"value": "baseball"
},
{
"id": "age",
"value": "20"
}
]
Note that this is the resulting block from:
json_object = json.loads(df['customFields'])
json_player = json_object['player']
I know that I can access individual strings within json_player
using the following code:
json_player[0]['value']
Which would return the string john
.
However, I would like to be able to call individual key-value pairs by name, rather than index, in order to protect myself if underlying JSON order changes. For example:
json_player['name']
would return john
. Can anyone tell me how I would do this?
>Solution :
You can easily construct the dictionary using a dict comprehension:
data = {
item["id"]: item["value"]
for item in json_player
}
print(data)
# => {'name': 'john', 'sport': 'baseball', 'age': '20'}