If you want to iterate over both keys and values of the dictionary, do this:
for key, value in data.items():
print(key, value)
Answer from Lior on Stack OverflowIf you want to iterate over both keys and values of the dictionary, do this:
for key, value in data.items():
print(key, value)
What error is it giving you?
If you do exactly this:
data = json.loads('{"lat":444, "lon":555}')
Then:
data['lat']
SHOULD NOT give you any error at all.
Videos
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]
In your for loop statement, Each item in json_array is a dictionary and the dictionary does not have a key store_details. So I modified the program a little bit
import json
input_file = open ('stores-small.json')
json_array = json.load(input_file)
store_list = []
for item in json_array:
store_details = {"name":None, "city":None}
store_details['name'] = item['name']
store_details['city'] = item['city']
store_list.append(store_details)
print(store_list)
If you arrived at this question simply looking for a way to read a json file into memory, then use the built-in json module.
with open(file_path, 'r') as f:
data = json.load(f)
If you have a json string in memory that needs to be parsed, use json.loads() instead:
data = json.loads(my_json_string)
Either way, now data is converted into a Python data structure (list/dictionary) that may be (deeply) nested and you'll need Python methods to manipulate it.
If you arrived here looking for ways to get values under several keys as in the OP, then the question is about looping over a Python data structure. For a not-so-deeply-nested data structure, the most readable (and possibly the fastest) way is a list / dict comprehension. For example, for the requirement in the OP, a list comprehension does the job.
store_list = [{'name': item['name'], 'city': item['city']} for item in json_array]
# [{'name': 'Mall of America', 'city': 'Bloomington'}, {'name': 'Tempe Marketplace', 'city': 'Tempe'}]
Other types of common data manipulation:
For a nested list where each sub-list is a list of items in the
json_array.store_list = [[item['name'], item['city']] for item in json_array] # [['Mall of America', 'Bloomington'], ['Tempe Marketplace', 'Tempe']]For a dictionary of lists where each key-value pair is a category-values in the
json_array.store_data = {'name': [], 'city': []} for item in json_array: store_data['name'].append(item['name']) store_data['city'].append(item['city']) # {'name': ['Mall of America', 'Tempe Marketplace'], 'city': ['Bloomington', 'Tempe']}For a "transposed" nested list where each sub-list is a "category" in
json_array.store_list = list(store_data.values()) # [['Mall of America', 'Tempe Marketplace'], ['Bloomington', 'Tempe']]
When e.g. q == tags, your print line becomes:
print "tags" + ': ' + [{"id":"1","name":"Downhill"}]
Python is strongly typed, so you can't implicitly concatenate a (unicode) string with a list. You need to be explicit about what you want to happen, i.e. that the list (data[q]) should be converted to a string:
print q + ': ' str(data[q])
or, much better, use str.format rather than string concatenation (or the old-fashioned % formatting):
print "{0}: {1}".format(q, data[q])
Here you have a small example:
import json
try:
# parse JSON string from socket
p = json.loads(msg)
except (ValueError, KeyError, TypeError):
logging.debug("JSON format error: " + msg.strip() )
else:
# remote control is about controlling the model (thrust and attitude)
com = "%d,%d,%d,%d" % (p['r'], p['p'], p['t'], p['y'])
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
Tested on Ideone.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
First you need to convert your json data to dict using json.loads, then you can access dict key easily.
In [23]: x = """
...: [
...: {"leagueId":"52dd22c0-0f4a-41e8-8au2-c81f66dacb43",
...: "leagueName":"League1",
...: "tier":"PLATINUM",
...: "queueType":"RANKED_SOLO",
...: "rank":"V",
...: "leaguePoints":0,
...: "wins":131,
...: "losses":117,
...: "hotStreak":false}
...: ]
...: """
In [24]: import json
In [25]: x = json.loads(x)
In [26]: x
Out[26]:
[{u'hotStreak': False,
u'leagueId': u'52dd22c0-0f4a-41e8-8au2-c81f66dacb43',
u'leagueName': u'League1',
u'leaguePoints': 0,
u'losses': 117,
u'queueType': u'RANKED_SOLO',
u'rank': u'V',
u'tier': u'PLATINUM',
u'wins': 131}]
In [27]: x[0]['tier']
Out[27]: u'PLATINUM'
In [28]:
The array is simply a list of length (1). So, you would retrieve the json dict by calling the array's first index - and then calling the get() method to retrieve the value in the dictionary:
responseJSON = {...}
f = responseJSON [0]['tier'] # value of f: 'PLATINUM'
You cannot do contents[:]["name"] since contents is a list is a dictionary with integer indexes, and you cannot access an element from it using a string name.
To fix that, you would want to iterate over the list and get the value for key name for each item
import json
contents = []
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
li = [item.get('name') for item in contents]
print(li)
The output will be
['Bulbasaur', 'Ivysaur']
This is not a real answer to the question. The real answer is to use a list comprehension. However, you can make a class that allows you to use specifically the syntax you tried in the question. The general idea is to subclass list so that a slice like [:] returns a special view (another class) into the list. This special view will then allow retrieval and assignment from all the dictionaries simultaneously.
class DictView:
"""
A special class for getting and setting multiple dictionaries
simultaneously. This class is not meant to be instantiated
in its own, but rather in response to a slice operation on UniformDictList.
"""
def __init__(parent, slice):
self.parent = parent
self.range = range(*slice.indices(len(parent)))
def keys(self):
"""
Retreives a set of all the keys that are shared across all
indexed dictionaries. This method makes `DictView` appear as
a genuine mapping type to `dict`.
"""
key_set = set()
for k in self.range:
key_set &= self.parent.keys()
return key_set
def __getitem__(self, key):
"""
Retreives a list of values corresponding to all the indexed
values for `key` in the parent. Any missing key will raise
a `KeyError`.
"""
return [self.parent[k][key] for k in self.range]
def get(self, key, default=None):
"""
Retreives a list of values corresponding to all the indexed
values for `key` in the parent. Any missing key will return
`default`.
"""
return [self.parent[k].get(key, default) for k in self.range]
def __setitem__(self, key, value):
"""
Set all the values in the indexed dictionaries for `key` to `value`.
"""
for k in self.range:
self.parent[k][key] = value
def update(self, *args, **kwargs):
"""
Update all the indexed dictionaries in the parent with the specified
values. Arguments are the same as to `dict.update`.
"""
for k in self.range:
self.parent[k].update(*args, **kwargs)
class UniformDictList(list):
def __getitem__(self, key):
if isinstance(key, slice):
return DictView(self, key)
return super().__getitem__(key)
Your original code would now work out of the box with just one additional wrap in UniformDictList:
import json
try:
with open("./simple.json", 'r') as f:
contents = UniformDictList(json.load(f))
except Exception as e:
print(e)
print(contents[:]["name"])
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!')