简体   繁体   English

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

[英]Converting string into valid json with Python

This string is returned to my app: 此字符串返回到我的应用程序:

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

The string is not valid JSON. 该字符串是无效的JSON。 All that's missing is the comma between the two valid JSON objects. 缺少的是两个有效JSON对象之间的逗号。

What's the best method to turn this string into valid JSON with Python? 使用Python将字符串转换为有效JSON的最佳方法是什么?

Edit: 编辑:

The string is the result of calling subprocess.check_output(), like for example this: 该字符串是调用subprocess.check_output()的结果,例如:

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

Since each command outputs a valid JSON object, I am receiving invalid JSON as a result. 由于每个命令输出一个有效的JSON对象,因此我收到了无效的JSON。

Inject commas in your shell command instead: 请在您的shell命令中插入逗号:

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

RegExp? 正则表达式?

import re
re.sub(r'}(\s*){', r'},\1{', my_string)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM