我需要将输出写入python中的json文件。 我在这里尝试了一些答案来写入json文件,但是由于某种原因,我找不到正确的格式,因此我需要将数据写入json文件。
我正在看的是:
'#fiche?username=' + username
如何用python编写这种格式?
谢谢
答案 0 :(得分:1)
首先,您的“ json”是错误的。我假设外部花括号应为方括号,因此您尝试保存列表。集合不是json格式的一部分。 假设不是this answer所不想要的,因为输出未格式化,则可以根据需要使用the documentation来格式化文件。例如:
Python 3.7.0 (default, Nov 21 2018, 10:19:24)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import json
In [2]: obj = [{
...: "Region": "BD",
...: "name": "bdfe",
...: "tyl": "cya",
...: "ice": "messi",
...: "fed": "bet",
...: },
...: {
...: "Region": "Toron",
...: "name": "Cana",
...: "tyl": "cyab",
...: "ice": "feed",
...: "fed": "not",
...: }]
In [3]: with open('data.json', 'w') as outfile:
...: json.dump(obj, outfile, indent=4)
...:
In [4]: !cat data.json
[
{
"Region": "BD",
"name": "bdfe",
"tyl": "cya",
"ice": "messi",
"fed": "bet"
},
{
"Region": "Toron",
"name": "Cana",
"tyl": "cyab",
"ice": "feed",
"fed": "not"
}
]
答案 1 :(得分:0)
在python中复制该代码非常简单。您所要做的就是将其转换为字典。这是转换后的输出:
import json
mydict = [{
"Region": "BD",
"name": "bdfe",
"tyl": "cya",
"ice": "messi",
"fed": "bet",
},
{
"Region": "Toron",
"name": "Cana",
"tyl": "cyab",
"ice": "feed",
"fed": "not",
}]
with open('data.json', 'w') as out:
json.dump(mydict, out, indent = 2)