I am trying to do something similar to the below code but instead of printing like last line in the code, I am looking for output to display as list of dicts.
import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
for jsonObj in f:
studentDict = json.loads(jsonObj)
studentsList.append(studentDict)
print("Printing each JSON Decoded Object")
for student in studentsList:
print(studentList) # Output is not looping , I get the following [{'id':
1, 'first_name': 'name1'}] but repeated 10 times in row instead it needs
to increment id until 10 with 1-10 id).
Thanks
If you simply want to print the list of dicts, why don't you just do print(studentsList)
It would look like this:
import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
for jsonObj in f:
studentDict = json.loads(jsonObj)
studentsList.append(studentDict)
print("Printing the list of JSON Decoded Objects")
print(studentList)
If you want your loop to work:
import json
studentsList = []
print("Started Reading JSON file which contains multiple JSON document")
with open('students.txt') as f:
for jsonObj in f:
studentDict = json.loads(jsonObj)
studentsList.append(studentDict)
print("Printing the list of JSON Decoded Objects")
for student in studentsList:
print(student)
This worked for me to avoid sorting alphabetically the list. pprint messes the sort so had to use below to make it work.
pprint(students_list, sort_dicts=False )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.