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.
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
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!')
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...
Related
I am creating a python project who are working with an api, the api return an json like this:
"1": "2018-10-13T08:28:38.809469028Z",
"result": [
{
"id":3027531,
"created_at":"2018-10-13T08:20:38.809469028Z",
"date":"2018-10-13T08:19:38Z",
"text":"banana",
}
],
I can get 1, but i can't get text in result, can someone help me?
I tried:
response.json()['result']['text']
response.json()['result'].text
response.json().result[0].text
Try this
response_json = response.json()
response_json["result"][0]["text"]
The value for result is a list of dictionaries. We take the first item in that list, and then we ask for the value of text.
Be aware that this assumes that response_json["result"] has at least one item. If it is empty, you will get an IndexError. You should probably check the length of response_json["result"] before using it. Here is an example of how this could be done:
response_json = response.json()
if response_json["result"]:
response_json["result"][0]["text"]
else:
print("result is empty")
d = {"1": "2018-10-13T08:28:38.809469028Z",
"result": [
{
"id":3027531,
"created_at":"2018-10-13T08:20:38.809469028Z",
"date":"2018-10-13T08:19:38Z",
"text":"banana",
}
]}
d['result'][0]['id'] # 3027531
d['result'][0]['text'] # banana
I am trying to get a JSON sub-schema's "name" from based off of its contents. This is kind of hard to explain, so an example would be better:
{
"dummy_name_1": {
"dummy_key_1": "unique_dummy_value_1",
"dummy_key_2": "dummy_value_2"
},
"dummy_name_2": {
"dummy_key_1": "unique_dummy_value_2",
"dummy_key_2": "dummy_value_2"
}
}
I want to get the name of dummy_name_1 (which would be "dummy_name_1") given the value of the key "dummy_key_1" (which would be "unique_dummy_value_1"). Basically, if I give the Python function I want "dummy_key_1" and "unique_dummy_value_1" as parameters, I want it to return the string "dummy_name_1".
Something like this? structure being your dict.
def get_dummy_name(dummy_key, dummy_value):
for dummy_name, content in structure.items():
if dummy_key in content.keys() and content[dummy_key] == dummy_value:
return dummy_name
try with this:
def get_category_name(key_name, key_value):
dictionary = {
"dummy_name_1": {
"dummy_key_1": "unique_dummy_value_1",
"dummy_key_2": "dummy_value_2"
},
"dummy_name_2": {
"dummy_key_1": "unique_dummy_value_2",
"dummy_key_2": "dummy_value_2"
}
}
for elem in dictionary.items():
if key_name in elem[1] and elem[1][key_name] == key_value:
return elem[0]
return False
response = get_category_name('dummy_key_1', 'unique_dummy_value_1')
How can i cut from such a string (json) everything before and including the first [ and everything behind and including the last ] with Python?
{
"Customers": [
{
"cID": "w2-502952",
"soldToId": "34124"
},
...
...
],
"status": {
"success": true,
"message": "Customers: 560",
"ErrorCode": ""
}
}
I want to have at least only
{
"cID" : "w2-502952",
"soldToId" : "34124",
}
...
...
String manipulation is not the way to do this. You should parse your JSON into Python and extract the relevant data using normal data structure access.
obj = json.loads(data)
relevant_data = obj["Customers"]
Addition to #Daniel Rosman answer, if you want all the list from JSON.
result = []
obj = json.loads(data)
for value in obj.values():
if isinstance(value, list):
result.append(*value)
While I agree that Daniel's answer is the absolute best way to go, if you must use string splitting, you can try .find()
string = #however you are loading this json text into a string
start = string.find('[')
end = string.find(']')
customers = string[start:end]
print(customers)
output will be everything between the [ and ] braces.
If you really want to do this via string manipulation (which I don't recommend), you can do it this way:
start = s.find('[') + 1
finish = s.find(']')
inner = s[start : finish]
I can't find the right search term to come up with an answer to this but I know it's a noob question. I'm accessing an API which returns either:
{
"Items":[
{
"Id":"12",
"Type":"Address",
"Highlight":"564754165545",
}
]
}
or sometimes:
{
"Items":[
{
"Id":"12",
"Type":"BuildingNumber",
"Highlight":"145454479854",
},
{
"Id":"12",
"Type":"Address",
"Highlight":"564754165545",
}
]
}
I need to get the "highlight" element data but only when type is address from a reply.
Thanks for your help and sorry I couldn't work out the name of the multiple rows to find this for myself.
Items is a list of dicts. According to your example, sometimes the list contains one item, and other times it contains two items.
for item in foo['Items']:
if item['Type'] == 'Address':
print (item['Highlight'])
Use following code
new_items = [ j for j in JSON['Items'] if j.get('Type') == 'Address' ]
JSON = {'Items' : new_items }
for only heighlight data
new_items = [ j.get('heighlight') for j in JSON['Items'] if j.get('Type') == 'Address' ]
To obtain a list of highlights objects with Address Type
[highlight for highlight in respose['Items'] if highlight['Type'] == 'Address']
I've got a json file that I've pulled from a web service and am trying to parse it. I see that this question has been asked a whole bunch, and I've read whatever I could find, but the json data in each example appears to be very simplistic in nature. Likewise, the json example data in the python docs is very simple and does not reflect what I'm trying to work with. Here is what the json looks like:
{"RecordResponse": {
"Id": blah
"Status": {
"state": "complete",
"datetime": "2016-01-01 01:00"
},
"Results": {
"resultNumber": "500",
"Summary": [
{
"Type": "blah",
"Size": "10000000000",
"OtherStuff": {
"valueOne": "first",
"valueTwo": "second"
},
"fieldIWant": "value i want is here"
The code block in question is:
jsonFile = r'C:\Temp\results.json'
with open(jsonFile, 'w') as dataFile:
json_obj = json.load(dataFile)
for i in json_obj["Summary"]:
print(i["fieldIWant"])
Not only am I not getting into the field I want, but I'm also getting a key error on trying to suss out "Summary".
I don't know how the indices work within the array; once I even get into the "Summary" field, do I have to issue an index manually to return the value from the field I need?
The example you posted is not valid JSON (no commas after object fields), so it's hard to dig in much. If it's straight from the web service, something's messed up. If you did fix it with proper commas, the "Summary" key is within the "Results" object, so you'd need to change your loop to
with open(jsonFile, 'w') as dataFile:
json_obj = json.load(dataFile)
for i in json_obj["Results"]["Summary"]:
print(i["fieldIWant"])
If you don't know the structure at all, you could look through the resulting object recursively:
def findfieldsiwant(obj, keyname="Summary", fieldname="fieldIWant"):
try:
for key,val in obj.items():
if key == keyname:
return [ d[fieldname] for d in val ]
else:
sub = findfieldsiwant(val)
if sub:
return sub
except AttributeError: #obj is not a dict
pass
#keyname not found
return None