【问题标题】:Python - Parsing through a JSON file and storing it as a variablePython - 解析 JSON 文件并将其存储为变量
【发布时间】:2021-04-22 00:19:51
【问题描述】:

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

【问题讨论】:

  • 您的文件正是一个 JSON 对象(假设对象之间确实有一个逗号)。只需执行with open('data2.json') as f: / obj = json.load(f)。然后您将获得整个列表。
  • 而且您无需致电str。所有这些东西都已经是字符串了。

标签: python json parsing


【解决方案1】:
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"])

【讨论】:

  • 感谢您的回复蒂姆。我完全按照您提到的方式进行了尝试,但是出现“TypeError:字符串索引必须是整数”错误。
  • 这只是意味着您的 JSON 数据看起来不像您在那里显示的那样。该数据工作正常。也许您应该再次检查您的数据。
【解决方案2】:

试试这个:

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'}]

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

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 2019-11-02
    • 2016-09-23
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多