How do I get the number of points in the json file to use in a for loop in python
Question:
I have this json file:
[
{ "results":
{ "points":
[
{ "name" : "s1" } ,
{ "name" : "s2" } ,
{ "name" : "j1" } ,
{ "name" : "n1" }
]
}
}
]
And this python code to read it:
import json
with open('test.json') as json_file:
data = json.load(json_file)
json_file.close()
for i in len(data[0]["results"]["points"]):
print(data[0]["results"]["points"][i]["name"],': ')
Which fails with the len statement. Is this what I should be using, or something else?
Answers:
In python, you usually don’t think your loop in term of indices. But you loop over your items directly
import json
from pathlib import Path
data = json.loads(Path("test.json").read_text())
for point in data[0]["results"]["points"] :
print(point)
If you still want the indices use enumerate()
for n, point in enumerate(data[0]["results"]["points"]) :
print(n, point)
By the way, if you use the context manager with
, you don’t need to explicitly close your file, that’s what the context manager does for you.
The error you got:
TypeError Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 for i in len(data[0]["results"]["points"]):
2 print(data[0]["results"]["points"][i]["name"],': ')
TypeError: 'int' object is not iterable
is telling you that for i in X
where X
in this case an int, is not iterable. Try this and you get the same error: for i in 4
. The fix is to enclose the len()
phrase with range()
:
for i in range(len(data[0]["results"]["points"])):
print(data[0]["results"]["points"][i]["name"],': ')
That code works, but it is messy. A cleaner, more Pythonic version is:
for point in data[0]["results"]["points"]:
print(point["name"], ":")
which produces the same output.
I have this json file:
[
{ "results":
{ "points":
[
{ "name" : "s1" } ,
{ "name" : "s2" } ,
{ "name" : "j1" } ,
{ "name" : "n1" }
]
}
}
]
And this python code to read it:
import json
with open('test.json') as json_file:
data = json.load(json_file)
json_file.close()
for i in len(data[0]["results"]["points"]):
print(data[0]["results"]["points"][i]["name"],': ')
Which fails with the len statement. Is this what I should be using, or something else?
In python, you usually don’t think your loop in term of indices. But you loop over your items directly
import json
from pathlib import Path
data = json.loads(Path("test.json").read_text())
for point in data[0]["results"]["points"] :
print(point)
If you still want the indices use enumerate()
for n, point in enumerate(data[0]["results"]["points"]) :
print(n, point)
By the way, if you use the context manager with
, you don’t need to explicitly close your file, that’s what the context manager does for you.
The error you got:
TypeError Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 for i in len(data[0]["results"]["points"]):
2 print(data[0]["results"]["points"][i]["name"],': ')
TypeError: 'int' object is not iterable
is telling you that for i in X
where X
in this case an int, is not iterable. Try this and you get the same error: for i in 4
. The fix is to enclose the len()
phrase with range()
:
for i in range(len(data[0]["results"]["points"])):
print(data[0]["results"]["points"][i]["name"],': ')
That code works, but it is messy. A cleaner, more Pythonic version is:
for point in data[0]["results"]["points"]:
print(point["name"], ":")
which produces the same output.