使用自定义变量Python生成Json文件

问题描述 投票:0回答:2

我正在尝试使用从input()从用户接收的变量生成一个json文件预设。我发现sorta的唯一方法 - 类似于我的是here,但它没有显示如何生成新的json文件。

输入的一个例子:

Enter the name of the json file:
>>>file

Enter the width:
>>>2

Enter the height:
>>>2

然后将这些输入转换为json文件,如下所示:

{
    "width": "2",
    "height": "2"
    "column": [
        {
            "0": "1255255255"
            "1": "1255255255"
        },
        {
            "0": "1255255255"
            "1": "1255255255"
        }
    ]
}

每个值列表对应一列,列表中的值是一行。如何生成足够的列和行以匹配宽度和高度?

即一栏:

        {
            "0": "1255255255"
            "1": "1255255255"
        }

一排:

            "0": "1255255255"

“1255255255”值并不重要,它只是一个占位符。

python json
2个回答
1
投票

您只需要生成所需结构的python表示(列表+ dicts等),然后使用json库将其转储到文件中。

所以在你的情况下,

import json

# Get these from input
filename = "test.json"
width = 3
height = 5
placeholder = 1255255255

obj = {
    "width": width,
    "height": height,
    "column": [{row: placeholder for row in range(height)} for col in range(width)]
}

with open(filename, "w") as out_file:
    json.dump(obj, out_file)

1
投票

我使用list和dict comprehension生成所需数量的字典并使用所需数量的键,然后我使用json.dump将字典序列化为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)))

测试:

Enter the name of the json file: test_json
Enter the width: 2
Enter the height: 2
JSON saved to file C:\Users\Bojan\.PyCharm2017.3\config\scratches\test_json.json

test_json.json文件的内容:

{
    "width": 2,
    "height": 2,
    "column": [
        {
            "0": 0,
            "1": 0
        },
        {
            "0": 0,
            "1": 0
        }
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.