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)
Answer from yash on Stack OverflowIn 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']]
Videos
Take a look at the json module. More specifically the 'Decoding JSON:' section.
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
You can try like below to get the values from json response:
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
Output:
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
Hi everyone. I'm really, really confused about parsing a JSON array.
For my script, I'll need to use a reverse geocoder, and I've decided to use Google's. I'm requesting a JSON, and it's returning this: https://developers.google.com/maps/documentation/geocoding/intro#reverse-example.
What I can't seem to figure out is the proper way of parsing it. I'm trying to extract the long_name in a few different types (for this example, let's say route, neighborhood, and administrative_area_level_2), and pass each long name for each type as their own string.
I'm completely lost on how to go about parsing this. I've tried json.loads, and doing a bunch of other things that fail in a "list indices must be integer", or unexpected results.
Right now, this is the nieve code I'm using to at least print long_name (about 30 times):
reverse_json = json.load(reader(reverseJSON))
# Excuse the debugging
print(reverse_json)
for data in reverse_json['results']:
address = data['address_components']
for data in address:
address = data['long_name']
print(address)And if I add on this to the final for loop:
if data['types'] == "['route']":
address = data['long_name']
print(address)I get nothing.
json.loads doesn't help, either. It just results in
TypeError: the JSON object must be str, bytes or bytearray, not 'StreamReader'
So, I'm stuck with trying to parse a JSON array, and to have "long_name" become a certain variable if a certain type occurs. It's confusing to me, hopefully it isn't to you.
A simple explanation and help would be appreciated.
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
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]