我想做一些类似下面的代码,但不是像代码中最后一行那样打印,而是希望输出显示为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).
谢谢你
如果你只是想打印dicts的列表,为什么不直接这样做呢?print(studentsList)
它看起来像这样。
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)
如果你想让你的循环工作,
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)
这对我来说很有效,避免了按字母顺序对列表进行排序,但pprint把排序搞乱了,所以不得不用下面的方法使其工作。
pprint(students_list, sort_dicts=False )