我正在尝试执行与以下代码类似的操作,但不是像代码中的最后一行那样打印, 我正在寻找要显示为字典列表的输出。
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).
谢谢
答案 0 :(得分:2)
如果您只想打印字典列表,为什么不只做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)
答案 1 :(得分:0)
这对我很有帮助,避免了按字母顺序对列表进行排序。 pprint弄乱了排序,因此必须在下面使用才能使其正常工作。
pprint(students_list,sort_dicts = False)