我正在尝试在 Jupyter Notebook 中编写一个函数,将字典输出为我可以粘贴到 VSCode launch.json 文件中的格式,并且具有正确的缩进。但如果我使用json.dumps,格式看起来不太好。def create_dict(): d = {} d["request"] = "launch" d["args"] = ["run", "param1=10", "param2=yes", "param3=100", "param4=0", "param5=no"] return json.dumps(d)结果是这样的。无论字符串有多长,它都只是一行:'{"request": "launch", "args": ["run", "param1=10", "param2=yes", "param3=100", "param4=0", "param5=no"]}'我以为我可以通过像这样缩进来解决这个问题,但结果是:def create_dict(): d = {} d["request"] = "launch" d["args"] = ["run", "param1=10", "param2=yes", "param3=100", "param4=0", "param5=no"] return json.dumps(d, indent=4)'{\n "request": "launch",\n "args": [\n "run",\n "param1=10",\n "param2=yes",\n "param3=100",\n "param4=0",\n "param5=no"\n ]\n}'这根本不是我想要的。我正在寻找的格式正是我从 return 字典中得到的格式,但我需要双引号才能与 json 兼容。def create_dict(): d = {} d["request"] = "launch" d["args"] = ["run", "param1=10", "param2=yes", "param3=100", "param4=0", "param5=no"] return d{'request': 'launch', 'args': ['run', 'param1=10', 'param2=yes', 'param3=100', 'param4=0', 'param5=no']}这正是我想要的格式,如何保留它并获得双引号?
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
我所需要的只是将 json 包装在print语句中:
def create_dict():
d = {}
d["request"] = "launch"
d["args"] = ["run", "param1=10", "param2=yes", "param3=100", "param4=0", "param5=no"]
return print(json.dumps(d, indent=4))
create_dict()
{
"request": "launch",
"args": [
"run",
"param1=10",
"param2=yes",
"param3=100",
"param4=0",
"param5=no"
]
}
添加回答
举报
0/150
提交
取消