Python 值不';不要添加到正确的位置
我正在尝试创建一个json文件,我一直在向其中添加值,但我面临一个问题,即我添加的值没有达到我希望它们达到的目的。 这段代码应该有助于让我的问题更清楚一些: 这就是我希望json看起来的样子:Python 值不';不要添加到正确的位置,python,json,Python,Json,我正在尝试创建一个json文件,我一直在向其中添加值,但我面临一个问题,即我添加的值没有达到我希望它们达到的目的。 这段代码应该有助于让我的问题更清楚一些: 这就是我希望json看起来的样子: { "Questions":[ { "text": "text", "c1": "text", "c2": "text&
{
"Questions":[
{
"text": "text",
"c1": "text",
"c2": "text", // #########################################
"c3": "text", // This is what i want the json to look like
"c4": "text", // #########################################
"answer": 1,
"way": "text",
"isImage": true,
"imagePath": "path"
}
]
}
这就是它最终的样子:
{
"Questions": [
{}
],
"text": "text",
"c1": "text",
"c2": "text",
"c3": "text", // #########################################
"c4": "text", // This is how it get generated by the code
"answer": 1, //##########################################
"way": "text",
"isImage": true,
"imagePath": "path"
}
这是我用来附加新值的代码
```
参考:
基本上你错过的只是数据[‘问题]]=[]我相信,这导致了奇怪的问题
import json
data = {}
data['Questions'] = []
data['Questions'].append({
"text": self.question_line.toPlainText(),
"c1": self.c1_line.toPlainText(),
"c2": self.c2_line.toPlainText(),
"c3": self.c3_line.toPlainText(),
"c4": self.c4_line.toPlainText(),
"answer": self.answer,
"way": self.answer_line.toPlainText(),
"isImage": self.isImage_check.isChecked(),
"imagePath": self.image_path_line.text(),
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
最终结果:
{
"Questions": [
{
"text": "test",
"c1": "test",
"c2": "test",
"c3": "test",
"c4": "test",
"answer": "test",
"way": "test",
"isImage": "test",
"imagePath": "test"
}
]
}
我用模拟数据对此进行了测试,效果很好,但如果您有任何问题,请告诉我“问题”值是一个列表,您应该将您愿意添加的json附加到您拥有的json中
看看这个:
json_obj={
“问题”:[
]
}
新数据={
“文本”:self.question\u line.toPlainText(),
“c1”:self.c1\u line.toPlainText(),
“c2”:self.c2_line.toPlainText(),
“c3”:self.c3\u line.toPlainText(),
“c4”:self.c4\u line.toPlainText(),
“答案”:自我回答,
“方式”:self.answer\u line.toPlainText(),
“isImage”:self.isImage_check.isChecked(),
“imagePath”:self.image\u path\u line.text(),
}
data=json_obj[“问题”]。追加(新的_数据)
json_obj[“问题”]=数据
我很抱歉没有设置格式,我不知道如何正确设置问题的格式:(文件数据[“问题”]。追加(新数据)
非常感谢,它确实有效!。
import json
data = {}
data['Questions'] = []
data['Questions'].append({
"text": self.question_line.toPlainText(),
"c1": self.c1_line.toPlainText(),
"c2": self.c2_line.toPlainText(),
"c3": self.c3_line.toPlainText(),
"c4": self.c4_line.toPlainText(),
"answer": self.answer,
"way": self.answer_line.toPlainText(),
"isImage": self.isImage_check.isChecked(),
"imagePath": self.image_path_line.text(),
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
{
"Questions": [
{
"text": "test",
"c1": "test",
"c2": "test",
"c3": "test",
"c4": "test",
"answer": "test",
"way": "test",
"isImage": "test",
"imagePath": "test"
}
]
}