我正在制作一个使用 JSON 对象生成 JSON 文件的程序。但是我在制作有效的 JSON 文件时遇到了一些麻烦。
我的目标是动态创建一个有效的 JSON 对象(参见下面的示例)。
所以,你开始用空的JSON对象:{ }
。然后 toruble 随之而来:添加一个 JSON 对象:
{
"Description": "just a making a object",
"Duration": "ongoing",
"Image": null,
"Process": null,
"day": "Saturday",
"end": "11:32:34.453694",
"start": "11:32:31.700324"
}
到那个空的 JSON 对象像这样:
{
"MonTask1": {
"Description": "just a making a object",
"Duration": "ongoing",
"Image": null,
"Process": null,
"day": "Saturday",
"end": "11:32:34.453694",
"start": "11:32:31.700324"
},
"MonTask2": {
"Description": "just a making a object",
"Duration": "ongoing",
"Image": null,
"Process": null,
"day": "Saturday",
"end": "11:32:34.453694",
"start": "11:32:31.700324"
}
}
python3中有没有办法做到这一点?
我的代码非常简单:
def setTask(Day, Time, Description, Duration = None, Process = None, Image = None):
task = {'day': Day, 'start': Time[0], 'end': Time[1], 'Description': Description, 'Duration': Duration, 'Process': Process, 'Image': Image}
return task
import json
class jsonObject:
def __init__(self, path):
self.filePath = path
with open(self.filePath, 'w') as jsonFile:
print('File was succesfully created!')
# task is the object made with the setTask method.
# Path is the filePath for the JSON file
def writeToFile(self, task, path):
jsonFile = open(path + '.json', 'a+')
json.dump(task, jsonFile, indent = 4, sort_keys=True)
提前致谢!
您可以使用与您需要的 json 等效的结构创建 Python 字典。以下是python shell的摘录:
>>> d = {}
>>> d['a'] = {}
>>> d['a']['b'] = 1
>>> d
{'a': {'b': 1}}
>>> d['a']['c'] = 2
>>> d
{'a': {'c': 2, 'b': 1}}
>>> import json
>>> json.dumps(d)
'{"a": {"c": 2, "b": 1}}'
>>> j = json.dumps(d)
>>> open('/tmp/a.txt','w').write(j)
23
>>>
$ cat /tmp/a.txt
{"a": {"c": 2, "b": 1}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句