gpt4 book ai didi

python - 将 python dict 转换为带有单反斜杠和双引号的字符串

转载 作者:行者123 更新时间:2023-12-02 16:34:33 25 4
gpt4 key购买 nike

我在 python 中有一个如下的字典

test_dict  = {'A': 'apple', 'B': 12345000, 'c': '2020-07-13 03:04:21.752566'}

我需要按如下方式格式化 json 输出,包括反斜杠和注释,int 值不需要反斜杠和注释

{
"zz":"zz",
"xx":"x",
"rawData":"{\"A\":\"apple\",\"B\":12345000,\"c\":\"2020-07-13 03:04:21.752566\"}"

}

我实现了以下功能

def construct_raw(abc):
start = "\"{"
end = "}"
delimiter = ","
dict_len = len(abc)
cnt = 0
for k, v in abc.items():
cnt = cnt + 1
if type(v) is str:
n = "\\\"" + v + "\\\""
else:
n = str(v)
start = start + "\\\"" + k + "\\\"" + ":" + n
if cnt != dict_len:
start = start + delimiter

start = start + end + "\""
return start

这为 rawData 产生了以下输出

"{\\"A\\":\\"apple\\",\\"B\\":12345000,\\"c\\":\\"2020-07-13 03:04:21.752566\\"}"

但这会导致字符串中出现双反斜杠如何解决这个问题?

最佳答案

使用json.dumps(test_dict)

In [123]: a = {}

In [124]: a["zz"] = "zz"

In [125]: a["xx"] = "x"

In [126]: a["rawData"] = json.dumps(test_dict)

In [127]: with open("a.json","w") as f:
...: json.dump(a,f)
...:

当您打开 a.json 时,您将看到反斜杠

{"zz": "zz", "xx": "x", "rawData": "{\"A\": \"apple\", \"B\": 12345000, \"c\": \"2020-07-13 03:04:21.752566\"}"}

关于python - 将 python dict 转换为带有单反斜杠和双引号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62925306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com