Python return json to PHP and use json_decode

php json stringify
how to get data from json array in php
convert array to json php
php read json file
php json foreach key => $value
json decode python
how to print json data in php
create json array in php

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?


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

PHP function.json-decode in Python, Decodes a JSON string. When TRUE, returned objects will be converted into associative arrays. depth Example #3 common mistakes using json_decode(). Python replacement for PHP's json_decode [ edit | history] This function will return false if the JSON encoded data is deeper than 127 elements.


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.

json_decode - Manual, NULL is returned if the json cannot be decoded or if the encoded data is if you are using json_decode to decode a string it HAS to be a propper json string: The json_decode () function is used to decode or convert a JSON object to a PHP object. json_decode ( string, assoc, depth, options) Parameter Values. Required. Specifies the value to be encoded. Optional. Specifies a Boolean value. When set to true, the returned object will be converted into an associative array. When set to false, it returns


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)

JSON PHP, to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. Objects in PHP can be converted into JSON by using the PHP function json_encode(): Before you send the request to the server, convert the JSON object into a Convert the request into an object, using the PHP function json_decode(). json_decode() Function Description. json_decode() function decodes a JSON string. Suppose you have obtained some data in JSON format and you want to convert it into PHP variable for the purpose of presenting that data to a user or use it for further programming, you have to use this function. PHP Version. PHP 5 >= 5.2.0, PECL json >= 1.2.0. Syntax:


PHP json_decode() Function, Store JSON data in a PHP variable, and then decode it into a PHP object: <?php $jsonobj = '{"Peter":35 Definition and Usage. The json_decode() function is used to decode or convert a JSON object to a PHP object. Return Value: Returns the value encoded in JSON in appropriate PHP type. Python Reference · W3. JSON is a standard format for data exchange, which is inspired by JavaScript. Generally, JSON is in string or text format. JSON stands for J ava S cript O bject N otation. The syntax of JSON: JSON is written as key and value pair. JSON is very similar to Python dictionary. Python supports JSON, and it has an inbuilt library as a JSON.


Python JSON: Encode(dump), Decode(load) json Data & File, dumps() method converts dictionary object of python into JSON string data return complex(objct['real'], objct['img']) return objct # use of json  Convert Python Object (Dict) to JSON. If you want to convert a Python Object to JSON use the json.dumps() method. Converting JSON data to Python objects. JSON data can be converted (deserialized) to Pyhon objects using the json.loads() function.


How to Parse JSON in PHP – Linux Hint, PHP uses json_encode() method to convert PHP array into JSON data. If you want to send or exchange small amount of data from one location or read JSON data from JSON object or any JSON file using PHP json_decode() How to Read and Write Json Files in Python · How to parse and process JSON in Python  PHP File explained: Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.