When restaurants is your list, you have to iterate over this key:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
Answer from Daniel on Stack OverflowWhen restaurants is your list, you have to iterate over this key:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
with open('data.json') as data_file:
data = json.load(data_file)
for restaurant in data['restaurant']:
print restaurant['restaurant']['name']
This way you will loop over the elements in the list of dictionaries inside your 'restaurants' field and output their names.
You were really close, what you were doing before was looping over all the main fields in your json file and print the name of the first restaurant every time (data['restaurants'][0] gives you the first restaurant in the list of restaurants... and you printed its name every time)
Python Parse JSON array - Stack Overflow
Parsing Json with for in loop in python - Stack Overflow
Looping through json array in python - Stack Overflow
how to can loop through an array of array in a json object in python - Stack Overflow
Videos
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']]
The reason why it's printing individual numbers is because the address is a string. Hence, it's not really each number that's being printed, but rather each letter of a string. Consider:
word = "abc"
for letter in word:
print(letter)
# prints:
# a
# b
# c
Therefore, it means somewhere you're assigning individual IP addresses to a variable, and then iterate through that variable (which is a string). Without you providing more code on how you get the ip_address variable, it's hard to say where the problem is.
One way to print your IP addresses (assuming you have them in a dict):
addresses = {"ip_address": [
"192.168.0.1",
"192.168.0.2",
"192.168.0.3"
]}
for address in addresses["ip_address"]: # this gets you a list of IPs
print(address)
Even if you have them somewhere else, the key insight to take away is to not iterate over strings, as you'll get characters (unless that's what you want).
Updated to address edits
Since I do not have the file (is it a file?) you are loading, I will assume I have exact string you posted. This is how you print each individual address with the data you have provided. Note that your situation might be slightly different, because, well, I do not know the full code.
# the string inside load() emulates your message
data = yaml.load('"ip_address": ["192.168.0.1", "192.168.0.2", "192.168.0.3"]')
ip_addresses = data.get('ip_address')
for address in ip_addresses:
print(address)
In your case ip_address = '192.168.0.1'
Are you sure you have the right value in ip_address?
Hi there, I am trying to read through a package.json file which is below. I want to read in specifically the dependencies and add them to key, value variables. I can't figure out how to read in nested object. If anyone can give me any tips?
{
"name": "untitled",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"express": "https://github.com/IAmAndyIE/expressjs.com.git"
},
}My current code is below.
import json
def test_document():
f = open('../untitled/package.json')
data = json.load(f)
for key, values in data.items():
if key == "dependencies":
print(values)
f.close()
if __name__ == '__main__':
test_document()Thanks
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