首页 > 解决方案 > Python - 解析 JSON 文件并将其存储为变量

问题描述

我对 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"
  }
]

标签: pythonjsonparsing

解决方案


import json

with open('data2.json', "r") as f:
    studentsList = json.load(f)


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

推荐阅读