Reputation: 83
Could anyone point me in the right direction for parsing some JSON in Python please, I haven't been able to find a way to do it
data = {
"profile": {
"properties": [
{
"name": "SavedNetworkAddress",
"type": "StrProperty",
"value": "111.111.111.111"
}, {
"name": "PlayerName",
"type": "StrProperty",
"value": "TEST"
}, {
"name": "bFirstSpawned",
"type": "BoolProperty",
"value": true
}
]
}
}
if I use the line as below it will return the 111.111.111.111
value in the 'SavedNetworkAddress'
section, however in my source data that particular section may not be in the first position of the array
print(data['profile']['properties'][0]['value'])
I would need to use something to get the value thats in the same section as 'SavedNetworkAddress' but I cant find out a way to do it in python
I've been able to get it to work in powershell but with the size of the files then it is taking a very long time to run
Thanks!
Upvotes: 0
Views: 57
Reputation: 1206
Json is analogous to dictionaries in Python. As the value to your key properties
is a json array (it's a list of dictionaries here, you can simply iterate through the list and see if the key name
matches to SavedNetworkAddress
Below is the code for the same:
for i in range(len(data['profile']['properties'])):
if data['profile']['properties'][i]['name'] == "SavedNetworkAddress":
print(data['profile']['properties'][i]['value'])
There is a small error in your data, Python won't be able to recognize true
. So please either convert true
to string or convert it to python keyword True
.
Upvotes: 3
Reputation: 65363
Indeed as you have a dictionary, another approach would be using dict.items()
and dict.keys()
methods consecutively such as
for i in data.items():
for k in data[i[0]].keys():
for v in data[i[0]][k]:
if v['name']=='SavedNetworkAddress':
print(v['value'])
Upvotes: 0
Reputation: 4446
I would do it like this,
next(x['value'] for x in data['profile']['properties'] if x['name'] == 'SavedNetworkAddress')
You basically loop for the elements in the list and return the value of the first element that matches the name
Upvotes: 1
Reputation: 2804
Try this:
print([print([d['value'] for d in data['profile']['properties'] if d["name"]=="SavedNetworkAddress"]))
You need to iterate all objects in properties
and check your condition
Upvotes: 0
Reputation: 59405
You should manually check each sub-dictionary in a loop:
for d in data['profile']['properties']:
if d['name'] == 'SavedNetworkAddress':
print(d['value'])
Upvotes: 1