gpt4 book ai didi

python - 使用 Python 将字符串转换为有效的 json

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:56 24 4
gpt4 key购买 nike

此字符串返回到我的应用程序:

[
{
"object1": "here",
"morekeys": "can also have objects as values"
}
{
"object2": "here",
"morekeys": "can also have objects as values"
}
]

字符串不是有效的 JSON。所缺少的只是两个有效 JSON 对象之间的逗号。

使用 Python 将此字符串转换为有效 JSON 的最佳方法是什么?

编辑:

该字符串是调用 subprocess.check_output() 的结果,例如:

my_string = "[" + subprocess.check_output("command1 && command2", shell=True, stderr=STDOUT) + "]"

由于每个命令都输出一个有效的 JSON 对象,因此我收到了无效的 JSON。

最佳答案

改为在您的 shell 命令中插入逗号:

my_string = "[{}]".format(
subprocess.check_output("command1 && echo ',' && command2",
shell=True, stderr=STDOUT, env=env))

关于python - 使用 Python 将字符串转换为有效的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34786476/

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