我使用list和dict comprehension生成具有所需键数的字典,然后使用json.dump将dictionary序列化为JSON格式的字符串(同时提供indent参数,否则,生成的JSON将只有一行),并将该字符串保存到用context manager(打开文件的首选方式)打开的文件中。在import json
import os
filename = input("Enter the name of the json file: ")
width = int(input("Enter the width: "))
height = int(input("Enter the height: "))
# Append .json if user did not provide any extension
if not os.path.splitext(filename)[1]:
filename += ".json"
with open(filename, 'w') as f:
json.dump({
"width": width,
"height": height,
"column": [
{
str(row_idx): 0 for row_idx in range(height)
}
for column_idx in range(width)
]
}, f, indent=4)
print("JSON saved to file {}".format(os.path.abspath(filename)))
测试:
^{pr2}$
test_json.json文件的内容:{
"width": 2,
"height": 2,
"column": [
{
"0": 0,
"1": 0
},
{
"0": 0,
"1": 0
}
]
}