<p>最后一个<code>file.json</code>示例不是有效的JSON。假设您只想用它来传递表单,您可以尝试扩展<a href="https://docs.python.org/3/library/json.html#json.JSONEncoder" rel="nofollow noreferrer">^{<cd2>}</a>,但是假设您的字典中没有嵌套结构,一种快速而肮脏的方法将是手动构造文件,即</p>
<pre><code>import json
your_data = [ # lets define some test data
{"key1.0": "value", "key2.0": "value"},
{"key1.1": "value", "key2.1": "value"},
{"key1.2": "value", "key2.2": "value"},
{"key1.3": "value", "key2.3": "value"},
]
with open("file.json", "w") as f: # open our file for writing
f.write("[") # begin a JSON array
if your_data: # a check to determine that our array is not empty
for element in your_data: # now loop through your elements one by one
json.dump(element, f) # JSON encode each element and write it to the file
f.write(",\n") # close the element entry with a comma and a new line
f.seek(-3, 1) # go back to the last separator to clear out the comma
f.write("]") # end the JSON array
f.truncate() # remove the rest, just in case
</code></pre>
<p>将产生:</p>
<pre>[{"key1.0": "value", "key2.0": "value"},
{"key1.1": "value", "key2.1": "value"},
{"key1.2": "value", "key2.2": "value"},
{"key1.3": "value", "key2.3": "value"}]</pre>