我正在开发一个测验式的程序来学习阿拉伯语。我现在需要从代码中删除问题并将它们存储在外部文件中 - 我正在考虑 .JSON。然而,我在从 python 访问某些问题或文件的部分时遇到困难,我不确定是否是因为我没有正确格式化我的 .JSON 文件,或者我的代码是否有错误。我已将两者都包含在下面。最终,我计划开设多节类(class),每节课有 3-4 个部分,其中包含 .JSON 文件中的问题。目前我只上了一节包含三个部分的课,只是为了确保我做对了事情。我在这里查看了另一个问题( How to read multi-level json ),但解决方案似乎对我不起作用。
如果我现在尝试运行代码,我会收到以下错误消息:
Traceback (most recent call last):
File "C:/LearningArabic/Test Programs/JSON open file test.py", line 10, in <module>
print(data["lesson 1"]["part two"])
KeyError: 'part two'
这是我的代码:
import json
import random
with open("C:\\LearningArabic\\LiblibArriby\\Lessons\\Arabic_Lessons.json", "r", encoding = "utf-8-sig") as read_file:
data = json.load(read_file)
for i in data["lesson 1"]["part one"]:
print (i["question"])
print(data["lesson 1"]["part two"])
for i in data["lesson 1"][0]["part two"]:
print (i["answer"])
question = (data["lesson 1"]["part one"])
questions = random.choice(question)
print(questions.get("question"))
行:
for i in data["lesson 1"]["part one"]:
print (i["question"])
可以工作并打印第一部分中的所有问题,但之后我收到上述错误。
这是我的 .JSON 文件:
{"lesson 1":[
{"part one": [
{"question": "What is the meaning of 'واد' ?",
"transliteration": "walid",
"answer": "boy"
},
{"question": "What is the meaning of 'بنت' ?",
"transliteration": "bint",
"answer": "girl"
},
{"question": "What is the meaning of 'رخل' ?",
"transliteration": "ragul",
"answer": "man"
},
{"question": "What is the meaning of 'ست' ?",
"transliteration": "sit",
"answer": "woman"
}
],
"part two": [
{"question": "What is the meaning of '2test1'?",
"transliteration": "phonix",
"answer": "21"
},
{"question": "What is the meaning of '2test2'?",
"transliteration": "phonix2",
"answer": "22"
}
],
"part three": [
{"question": "What is the meaning of '3test1'?",
"transliteration": "phonix",
"answer": "31"
},
{"question": "What is the meaning of '3test2'?",
"transliteration": "phonix2",
"answer": "32"
}
]}
]}
最佳答案
以下 JSON 文件:
{"lesson 1":
{"part one": [
{"question": "What is the meaning of 'ست' ?",
"transliteration": "sit",
"answer": "woman"
}
],
"part two": [
],
"part three": [
{"question": "What is the meaning of '3test2'?",
"transliteration": "phonix2",
"answer": "32"
}
]}
}
使用以下 python 代码:
导入json
with open("test.json", "r", encoding = "utf-8-sig") as read_file:
data = json.load(read_file)
for i in data["lesson 1"]["part one"]:
print (i["question"])
for i in data["lesson 1"]["part two"]:
print (i["answer"])
按预期工作。 print(data["第一课"]["第二部分"])
也有效。
您需要删除“lesson1:
后面的方括号并整理变量的索引
关于python - 如何创建多级json文件,然后从python读取特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52346113/