I believe you probably meant:
from __future__ import print_function
for song in json_object:
# now song is a dictionary
for attribute, value in song.items():
print(attribute, value) # example usage
NB: You could use song.iteritems instead of song.items if in Python 2.
I believe you probably meant:
from __future__ import print_function
for song in json_object:
# now song is a dictionary
for attribute, value in song.items():
print(attribute, value) # example usage
NB: You could use song.iteritems instead of song.items if in Python 2.
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.
Videos
My Json is of the following format:
https://pastebin.com/KUKHHh2e
The numbers in this json are many as are the dates. I am trying to iterate through this to create a single list of dictionaries that contains all of the information in the dictionary that is 3 layers deep in the json.
I have made a loop that is n3 but it seems highly inefficient given i have around 30,000 iterations to make.
What are my options here?
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
You are assuming that i is an index, but it is a dictionary, use:
for item in data["Results"]:
print item["Name"]
Quote from the for Statements:
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
you are iterating through the dictionary not indexes so you should either use.
for item in data["Results"]:
print item["Name"]
or
for i in range(len(data["Results"])):
print data["Results"][i]["Name"]
data should be an ordinary collection at this point, so you'd iterate over it the same way you'd iterate over any other list/dict/whatever. The fact that it came from load doesn't incur any extra requirements on your part.
Here's an example that uses loads, which is similar in principle:
import json
my_json_data = "[1,2,3]"
data = json.loads(my_json_data)
for item in data:
print(item)
Result:
1
2
3
Edit: if you're asking "how to I iterate over all the values in my data, including the ones contained inside deeply nested collections?", then you could do something like:
import json
my_json_data = """[
1,
{
"2": 3,
"4": [
"5",
"6",
"7"
]
},
8,
9
]"""
def recursive_iter(obj):
if isinstance(obj, dict):
for item in obj.values():
yield from recursive_iter(item)
elif any(isinstance(obj, t) for t in (list, tuple)):
for item in obj:
yield from recursive_iter(item)
else:
yield obj
data = json.loads(my_json_data)
for item in recursive_iter(data):
print(item)
Result:
1
5
6
7
3
8
9
Edit: You can also keep track of the keys needed to navigate to each value, by passing them through the recursive calls and adding new keys to the collection as you pass over them.
def recursive_iter(obj, keys=()):
if isinstance(obj, dict):
for k, v in obj.items():
yield from recursive_iter(v, keys + (k,))
elif any(isinstance(obj, t) for t in (list, tuple)):
for idx, item in enumerate(obj):
yield from recursive_iter(item, keys + (idx,))
else:
yield keys, obj
data = json.loads(my_json_data)
for keys, item in recursive_iter(data):
print(keys, item)
Result:
(0,) 1
(1, '2') 3
(1, '4', 0) 5
(1, '4', 1) 6
(1, '4', 2) 7
(2,) 8
(3,) 9
The previous solution is wrong, because if there is a leaf element that is [] or () or {}, it will not be printed (the 'for' loop to enumerate the object will not run). Here is a corrected solution:
def recursive_iter(obj, keys=()):
if isinstance(obj, dict):
if len(obj) == 0:
yield keys, obj
else:
for k, v in obj.items():
yield from recursive_iter(v, keys + (k,))
elif any(isinstance(obj, t) for t in (list, tuple)):
if len(obj) == 0:
yield keys, obj
else:
for idx, item in enumerate(obj):
yield from recursive_iter(item, keys + (idx,))
else:
yield keys, obj
a = {'a': (), 'b': [], 'c': 123, 'd': {}}
for i,j in recursive_iter(a):
print(i,j)
This code prints:
('a',) ()
('b',) []
('c',) 123
('d',) {}