1

According to this mine question Python find value in array by filter

This is what I have done

data = {}

for result in results:
    if 'stackoverflow.com' in result['serp_url']:
        data['url'] = result['serp_url']
        data['rank'] = result['serp_rank']
        data['query'] = result['query']
        print(data)
        exit

This is PHP code

$test = shell_exec("python3 py.py");
var_dump($test);

And this is output

/home/user/Desktop/pyphp/index.php:4:string '{'url': 'https://stackoverflow.com/', 'rank': 1, 'query': 'stackoverflow'}
{'url': 'https://www.quantcast.com/stackoverflow.com', 'rank': 36, 'query': 'stackoverflow'}
' (length=168)

When I use json_decode($test) I'm getting null as output.

What's the best way to use as json or array output from Python in PHP?

15
  • 1
    could You please do echo $test;, not var_dump()? Commented Sep 27, 2018 at 10:44
  • This is output {'url': 'https://stackoverflow.com/', 'rank': 1, 'query': 'stackoverflow'} {'url': 'https://www.quantcast.com/stackoverflow.com', 'rank': 36, 'query': 'stackoverflow'} as one string Commented Sep 27, 2018 at 10:45
  • That's not valid json, that's your problem. You should wrap it into an array. Commented Sep 27, 2018 at 10:45
  • so this is not a correct JSON syntax... you got like 2 objects in one... {'url': 'https://stackoverflow.com/', 'rank': 1, 'query': 'stackoverflow'} and {'url': 'https://www.quantcast.com/stackoverflow.com', 'rank': 36, 'query': 'stackoverflow'} Commented Sep 27, 2018 at 10:46
  • 1
    @dogano it won't help :) json_decode() fails, doesn't really matter if it returns object or array, as it fails Commented Sep 27, 2018 at 10:48

4 Answers 4

1

Thank you all for comments! According to that, I kind figure out solution.

Python script

data = {}
for result in results:
    if 'stackoverflow.com' in result['serp_url']:
        data['url'] = result['serp_url']
        data['rank'] = result['serp_rank']
        data['query'] = result['query']
        print(json.dumps(data))
        exit

PHP script

exec("python3 py.py", $output);

$test = [];

foreach($output as $key => $out) {
    $test[$key] = json_decode($out, true);
    print_r("Rank: " . $test[$key]['rank'] ." - ". $test[$key]['url']."<br>");
}

Output

Rank: 1 - https://stackoverflow.com/
Rank: 36 - https://www.quantcast.com/stackoverflow.com
Sign up to request clarification or add additional context in comments.

Comments

0

You don't even have to even use Json package of Python. Here is little tweek. In Python and PHP code.

# Your py.py Looks Below: 
data = {}
data["aa"] = 100
# You can create any Valid Dictionary
print data

and Your Php File will have this code

<?php
    $test = shell_exec("python py.py");
    echo json_decode(json_encode($test));
    // $test itself is a json String you even dont need encode/decode
?>

And The Result in my Terminal got {'aa': 100} Which is Expected and you want.

Now Important Point is that shell_exec command will give you the string which is converted from Dictionary and fortunately, That string itself is a JSON, That why json_decode is returning NULL.

Above both Snippet works fine. Check them.

2 Comments

Thanks a lot! This will be useful as well!
Great I hope it should solve your problem. Can you accept as the answer?
0

Python file:

import json
import base64

j_data = {
"name": "wick",
"age": 24,
}

jso_en = json.dumps(j_data , indent=4)
#encode with base64
res_arr_bytes = jso_en.encode("ascii")  
base64_bytes = base64.b64encode(res_arr_bytes)
base64_enc = base64_bytes.decode("ascii")
print(base64_enc)

PHP file:

$command = escapeshellcmd("python3 test.py");
$json_out = shell_exec($command);
$json_data = json_decode(base64_decode($json_out), true);
echo $json_data['name'];

output from php:

wick

Comments

-1

The json you're generating is not valid (free objects outside of an array and strings between single quotes).

In your python code you should append your data objects to an array as you're creating them. Here's a rough attempt at solving your issue

import json

data = [] # use a list to keep your objects

for result in results:
    if 'stackoverflow.com' in result['serp_url']:
        record = {}
        record['url'] = result['serp_url']
        record['rank'] = result['serp_rank']
        record['query'] = result['query']
        data.append(record)
        # exit # <-- this doesn't seem correct, TBH
json.dumps(data)

4 Comments

In my opinion it's not a reason why it returns 2 objects at once... ofc objects won't aggregate, but still the problem is somewhere else.
@FlashThunder IMHO, the problem is that what OP posted is not what they're actually using to get that output (that's why I commented out the exit). I'll keep my answer here anyway just in case and I will understand and accept any downvote that comes my way :)
You may be right, that's why I only posted a comment.
Thanks for this, but didn't work, since I got null when executed script.

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.