1

How do I parse a dict output from a python script to a PHP array? My PHP file contains the line exec('/bin/python ~/somescript.py', $out, $err);. And my python script prints a dict with something like

d = {0: "a", 7: "d", 23: ["e", "z"]}
print(d)

But this doesn't work, $out[0] in my PHP file is just a really long string an array. I've also tried to use print(json.dumps(d)), same result (but with escaped " ).

3
  • It shouldn't be json.loads(d) as .dumps is used for encoding a python object to a json string (what I need). And .loads is used for decoding a json string to a python object. See docs.python.org/3/library/json.html Commented May 10, 2021 at 9:34
  • $out is the output of the python script. See php.net/manual/de/function.exec.php. Commented May 10, 2021 at 9:48
  • Great, this worked, thanks! Commented May 10, 2021 at 10:04

1 Answer 1

1

Use print(json.dumps(d)) in your Python script. Trim the dumps output by passing it separators=(',', ':') with the default indent=None so that the JSON is dumped to one line. So:

print(json.dumps(d, indent=None, separators=(',', ':')))

After that json_decode($out) or json_decode($out[0]) in your PHP script.

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.