1

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. All that's missing is the comma between the two valid JSON objects.

What's the best method to turn this string into valid JSON with Python?

Edit:

The string is the result of calling subprocess.check_output(), like for example this:

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.

6
  • 1
    Are there more examples? What happens when there are more than two elements? Is this the case for all lists or only top-level lists. Commented Jan 14, 2016 at 9:59
  • The string is received with subprocess.check_output(). The string is the result of concatenating multiple commands with '&&' (and wrapping the result with [ ]). Since each tool produces its own valid JSON output, I am receiving this invalid concatenated json. There could be more than two elements (in which case there would be several commas missing in between the valid json objects). Commented Jan 14, 2016 at 10:06
  • 2
    That's.... so wrong. At the very least then add commas in that shell command, stripping the last comma is far easier. Commented Jan 14, 2016 at 10:10
  • But each command can be executed on its own. If I add a trailing comma, then the individual tools would produce invalid JSON. Commented Jan 14, 2016 at 10:11
  • I didn't say the commands themselves should add the trailing comma, I said the shell command you used to concatenate their output should. Commented Jan 14, 2016 at 10:13

2 Answers 2

3

Inject commas in your shell command instead:

my_string = "[{}]".format(
    subprocess.check_output("command1 && echo ',' && command2",
                            shell=True, stderr=STDOUT, env=env))
Sign up to request clarification or add additional context in comments.

Comments

1

RegExp?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.