I have a simple JSON file which is essentially a long string like this:
{"quickGang": {"scopeIds": [2,9],"name": "","channelIds": [],"enabled": false},"modelVersion": 0,"links": [],"applyOnConnect": false}
I am able to print out the contents of the file in separate lines as shown further down.
However when I attempt to work with the contents in a FOR loop, it is reading in each character at a time instead of each line.
How can I read a line at a time?
Here’s my code:
import os
import json
path="C:\\Users\\Mick T\\Downloads\\gangs.json"
with open(path, 'r') as json_file:
file_name = os.path.basename(path)
print (file_name)
json_object = json.load(json_file)
json_formatted_str = json.dumps(json_object, indent=2)
print(json_formatted_str)
i=1
for line in json_formatted_str:
print(line, ' ', end='')
print (i)
i = i + 1
Here’s the first part of the output with a counter included:-
C:\Users\Mick T\Downloads>python forum1.py
gangs.json
{
"quickGang": {
"scopeIds": [
2,
9
],
"name": "",
"channelIds": [],
"enabled": false
},
"modelVersion": 0,
"links": [],
"applyOnConnect": false
}
{ 1
2
3
4
" 5
q 6
u 7
i 8
c 9
k 10
G 11
a 12
n 13
g 14
" 15
json_object["quickGang"]. You must not dump it back into formatted string and iterate over it. Work with the dict you receive after you load the JSON. Otherwise what is the purpose of working with e.g."scopeIds": [line?