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
Answer from Roee Anuar on Stack OverflowHere 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!')
The Fastest method to find element in JSON (Python) - Stack Overflow
Accessing data from a json array in python - Stack Overflow
Find a value of Key in Json Array - Python - Stack Overflow
Find a value in JSON using Python - Stack Overflow
Here’s an easy way to do it:
def function(json_object, name):
for dict in json_object:
if dict['name'] == name:
return dict['price']
If you are sure that there are no duplicate names, an even more effective (and pythonic) way to do it is to use list comprehensions:
def function(json_object, name):
return [obj for obj in json_object if obj['name']==name][0]['price']
from json import loads
json = """[
{
"name":"Apple",
"price":2,
"have":0,
"max":36
},
{
"name":"Pineapple",
"price":5,
"have":6,
"max":17
}
]"""
parsedJson = loads (json)
def jsonname (name):
for entry in parsedJson:
if name == entry ['name']:
return entry ['price']
The error message is correct.
key = json.loads(response['password'])
print(key[0]),
The format of json is string. You need to convert the string of a json object to python dict before you can access it.
i.e.: loads(string) before info[key]
key = json.loads(response)['password']
print(key[0])
Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).
so assuming your response is actually a string (eg that was retrieved from a HTTP request/endpoint) then you deserialise it with json.loads (the function is basically load from string), then you've got a map with a 'password' key, that is an array, so grab the first element from it.
import json
resp = '{ "password": [ "Ensure that this field has atleast 5 and atmost 50 characters" ] }'
print json.loads(resp)['password'][0]
w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.
The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()]
# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None
The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.
w = None
for item in y['filters']:
if 'filterB' in item:
w = item['filterB']
break
print(w) # val1
Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried
all_dict = dict()
for item in y['filters']:
all_dict.update(item)
# Replace the list of dicts with the dict
y['filters'] = all_dict
w = y['filters']['filterB']
print(w) # val1
If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:
y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
if 'filterB' in item:
all_w.append(item['filterB'])
Or, as a list-comprehension:
all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']
Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension
You have to iterate over the list of dictionaries and search for the one with the given id_number. Once you find it you can print the rest of its data and break, assuming id_number is unique.
data = [
{
"id_number": "SA4784",
"name": "Mark",
"birthdate": None
},
{
"id_number": "V410Z8",
"name": "Vincent",
"birthdate": "15/02/1989"
},
{
"id_number": "CZ1094",
"name": "Paul",
"birthdate": "27/09/1994"
}
]
for i in data:
if i['id_number'] == 'V410Z8':
print(i['birthdate'])
print(i['name'])
break
If you have control over the data structure, a more efficient way would be to use the id_number as a key (again, assuming id_number is unique):
data = { "SA4784" : {"name": "Mark", "birthdate": None},
"V410Z8" : { "name": "Vincent", "birthdate": "15/02/1989"},
"CZ1094" : {"name": "Paul", "birthdate": "27/09/1994"}
}
Then all you need to do is try to access it directly:
try:
print(data["V410Z8"]["name"])
except KeyError:
print("ID doesn't exist")
>> "Vincent"
Using lambda in Python
data = [
{
"id_number": "SA4784",
"name": "Mark",
"birthdate": None
},
{
"id_number": "V410Z8",
"name": "Vincent",
"birthdate": "15/02/1989"
},
{
"id_number": "CZ1094",
"name": "Paul",
"birthdate": "27/09/1994"
}
]
Using Lambda and filter
print(list(filter(lambda x:x["id_number"]=="CZ1094",data)))
Output
[{'id_number': 'CZ1094', 'name': 'Paul', 'birthdate': '27/09/1994'}]
json_arr = [
{
'Clothes': [
{
'id': '32705111',
'describes': 'no problem'
}
]
},
{
'Dress': [
{
'id': '32705111',
'describes': 'no outfit'
}
]
}
]
for d in json_arr:
for name, array in d.items():
globals()[name] = array
Try below code, I guess this is what you are looking for
new_lst = []
for i in json_array:
for name, array in i.items():
value = ''.join(str(array))
result = name+value
new_lst.append(result)
print(new_lst)
Output -
["Clothes[{'id': '32705111', 'describes': 'no problem'}]", "Dress[{'id': '32705111', 'describes': 'no outfit'}]"]
I have an undesirable JSON object that I can't modify:
{
"programs": [
],
"streams": [
{
"index": 0,
"codec_name": "hevc",
"codec_type": "video"
},
{
"index": 1,
"codec_name": "aac",
"codec_type": "audio"
},
{
"index": 2,
"codec_name": "opus",
"codec_type": "audio"
},
{
"index": 3,
"codec_name": "ac3",
"codec_type": "audio"
},
{
"index": 4,
"codec_name": "ass",
"codec_type": "subtitle"
},
{
"index": 5,
"codec_name": "ttf",
"codec_type": "attachment"
}
]
}
This is psudo json from the very real output of ffprobe -loglevel error -show_entries format:stream=index,stream,codec_type,codec_name -of json FILENAME
I need to get the first codec_name from the lowest index of the codec_type: audio.
In this case, index 1, 2, and 3 are all of codec_type: audio, so the lowest index/first instance would be 1 and my codec_name would be aac.
Any ideas on how to move forward on a problem like this? I can't seem to find any stackoverflow threads with anything similar.
----------------------------
EDIT, solution here: https://www.reddit.com/r/learnpython/comments/16af8zf/comment/jz74hc9/?utm_source=share&utm_medium=web2x&context=3
Thank you u/shiftybyte, u/djshadesuk!!!