I'm using a website's API
to get information. It outputs 100 values.
What is the best practice of searching for a specific value in this array?
The array looks something like this:
{
"success":true,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}
I try searching for the data using this snippet I found elsewhere, however it does not work:
for name in (r.json()['data']['array'][0]['name']):
if r.json()['data']['array'][0] == s_name:
ident = r.json()['data']['array'][0]['id']
name = r.json()['data']['array'][0]['name']
print (name + ' - ' + ident)
else:
print ('Nothing was found.')
So if I was trying to reference Value1
how would I do this using Python
?
Please note: I'm a rookie developer, first time using Json
, not very experienced with Python
.
All help is greatly appreciated.
So first thing you need to import the 'json' module into the file. Then create a simple json object string in python and assign it to a variable. Now we will use the loads() function from 'json' module to load the json data from the variable. We store the json data as a string in python with quotes notation.
Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .
Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.
Not sure where that piece of code came from but it looks very wrong.
Just looking at the structure you can do something like:
for attrs in r.json()['data']['array']:
if attrs['name'] == s_name:
ident = attrs['id']
name = attrs['name']
print(name, '-', ident)
break
else:
print('Nothing found!')
Here is a one-liner example for searching:
aaa = {
"success":True,
"data":
{
"array":
[
{
"id":"1","name":"Value1"
},
{
"id":"2","name":"Value2"
}
]
}
}
[a['name'] for a in aaa['data']['array'] if a['id']=='1']
This will return all the found cases, or an empty array if nothing is found
Your code can be simplified a lot:
# no need to call `r.json` so many times, can simply save it to a variable
json_data = r.json()
for item in json_data["data"]["array"]:
if item["name"] == "Value1":
# do something...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With