2

The code runs a script using a subprocess and returns json. If I print the json, it comes back fine, but when I try to load it with json.loads, there is this error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
output, err = p.communicate()
outstring = str(output)
print(output) # This works
return json.loads(outstring) # This has the error

Edit: I tried outstring.json() but got this error: AttributeError: 'str' object has no attribute 'json'

6
  • Didn't you ask the same question a few minutes ago? Commented Nov 2, 2020 at 0:23
  • 1
    The output is probably not JSON or has a trailing newline. Commented Nov 2, 2020 at 0:27
  • What does the print(output) look like? From the error, it seems like output is the empty string. Commented Nov 2, 2020 at 0:27
  • Attach the console output Commented Nov 2, 2020 at 0:28
  • Come to think of it, that would make the print just an empty line. What is print(repr(output))? Commented Nov 2, 2020 at 0:28

1 Answer 1

1

You print output but then try to decode outstring. In fact, you got a bytes object back from stdout. When you made it into a string, you got the string represenation of the bytes object. So, if your json is "foo", you tried to decode "b'foo'". If your command is outputing utf-8, you can just pass it to json.loads. Otherwise you need to decode it first.

p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
output, err = p.communicate()
return json.loads(output)

or

p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
output, err = p.communicate()
outstr = output.decode("utf-16") # or whatever encoding
return json.loads(outstr)
Sign up to request clarification or add additional context in comments.

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.