Iterating through a JSON object
Your loading of the JSON data is a little fragile. Instead of:
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
you should really just do:
json_object = json.load(raw)
You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0]
, you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:
, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song]
.
None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.
Looping through JSON object with a conditional
That should work for you:
for q in content:
if q['collection']['location'] == '/450/':
data.append(q)
print(data)
If you go with for
loop with for col in q['collection']
, you just iterate over keys inside q['collection']
, so cols = ['archived', 'authority_level', ...]
.
Loop through JSON data in Python
The solution of diek is the one that worked for me, edited my post because of this. The better code is:
import requests
import json
response = requests.get("")
data =response.text
parsed=json.loads(data)
for product in parsed['products']:
print(product['id'])
The output will look as follow:
66057248
66057245
66057242
66057239
66057236
66057233
66057230
66057227
66057224
How to loop through JSON data using python?
You need to loop through the events not the individual deadline time.
Replace
for item in data['events']['deadline_time']:
print(item)
With
for item in data['events']:
print(item['deadline_time'])
How to loop through json data with multiple objects
You need to iterate the data to extract the host
and username
values so that you can zip
them to the remote
list:
data = [
{"host" : "192.168.0.25", "username":"server2", "path":"/home/server/.ssh/01_id"},
{"host" : "192.168.0.26", "username":"server3", "path":"/home/server/.ssh/01_id"}
]
hosts_users = [(d['host'], d['username']) for d in data]
remote = [1, 2]
for remote, (host, username) in zip(remote, hosts_users):
print(remote, host, username)
Output:
1 192.168.0.25 server2
2 192.168.0.26 server3
Looping through a JSON array in Python
When restaurants
is your list, you have to iterate over this key:
for restaurant in data['restaurants']:
print restaurant['restaurant']['name']
Iterating through a JSON object after first level
This happens because you are iterating through the dictionary created by your JSON at a level too high. You can go inside the dictionary at key = 'data' by using jsonObject["data"], then iterate like you did.
for key in jsonObject["data"][0]:
value = jsonObject["data"][0][key]
print("The key and value are {} = {}".format(key, value))
You could even write this more concisely using the .items() built-in method for dictionaries:
for key,value in jsonObject["data"][0].items():
print("The key and value are {} = {}".format(key, value))
Related Topics
Python 2D List Performance, Without Numpy
How to Serialize Sqlalchemy Result to Json
Printing Simple Diamond Pattern in Python
Python Sockets Multiple Messages on Same Connection
How to Drop Rows of Pandas Dataframe Whose Value in a Certain Column Is Nan
How to Select Percentage of Rows in Pandas Dataframe
Exclude First Row When Importing Data from Excel into Python
Running Multiple Commands Simultaneously from Python
Python Does Not Match Format '%Y-%M-%Dt%H:%M:%S%Z.%F'
Loop Through Json Data in Python
How to Flatten a Hierarchical Index in Columns
How to Read Image Data from a Url in Python
Finding the Two Closest Numbers in a List Using Sorting
Python Data Frame How to Find the Local Maximum in a 2D Array
Numpy Import Throws Attributeerror: 'Module' Object Has No Attribute 'Core'