Python—通过JSON文件进行解析并将其存储为变量

Python—通过JSON文件进行解析并将其存储为变量,python,json,parsing,Python,Json,Parsing,我对Python不太熟悉,我试图理解如何打开一个JSON文件,其中包含需要在Python文件中打开的键和值,并操作每个值。最后,我希望将这些值分配到某个地方,以便使用它们来制作Python GUI(tkinter) 到目前为止,我有这个测试,但得到一个错误: import json with open('data2.json', "r") as f: for jsonObj in f: studentDict = json.load(jsonObj)

我对Python不太熟悉,我试图理解如何打开一个JSON文件,其中包含需要在Python文件中打开的键和值,并操作每个值。最后,我希望将这些值分配到某个地方,以便使用它们来制作Python GUI(tkinter)

到目前为止,我有这个测试,但得到一个错误:

import json

with open('data2.json', "r") as f:
    for jsonObj in f:
        studentDict = json.load(jsonObj)
        studentsList.append(studentDict)


print("Printing each JSON things..")
for student in studentsList:
    print(str(student["name"], student["id"], student["year"]))
=====================================================================================

我的JSON文件内容如下:

[
  {
   "name": "jane",
   "id": "jdoe",
   "year": "sophomore"

  }
  {
   "name": "john",
   "id": "jsmith",
   "year": "senior"
  }
]
请尝试以下方法:

studentsList = []

with open('data2.json', "r") as f:
    for jsonObj in f:
        studentDict = json.loads(jsonObj)
        studentsList.append(studentDict)

print("Printing each JSON things..")
for student in studentsList[0]:
    print(str(student["name"], student["id"], student["year"]))
这是附加到studentsList后得到的嵌套列表:

[[{'name': 'jane', 'id': 'jdoe', 'year': 'sophomore'},
  {'name': 'john', 'id': 'jsmith', 'year': 'senior'}]]
因此,为了使循环正常工作,必须在调用字典键之前索引一个级别。studentsList[0]为您提供:

[{'name': 'jane', 'id': 'jdoe', 'year': 'sophomore'},
 {'name': 'john', 'id': 'jsmith', 'year': 'senior'}]

现在,循环中的每个迭代都将引用一个dictionary对象,您可以开始调用它的键而不会出现任何错误。

您的文件正好是一个JSON对象(假设对象之间确实有一个逗号)。只需将open('data2.json')作为f:/
obj=json.load(f)
。然后你就有了完整的列表。你不需要调用
str
。所有这些都是字符串。谢谢你的回复。我尝试了你刚才提到的方法,但是我得到了一个“TypeError:字符串索引必须是整数”错误。这只是意味着你的JSON数据看起来不像你在那里显示的那样。这些数据运行良好。也许你应该再次检查你的数据。
[{'name': 'jane', 'id': 'jdoe', 'year': 'sophomore'},
 {'name': 'john', 'id': 'jsmith', 'year': 'senior'}]