Skip to content

sending the json data from python to php

An answer to this question on Stack Overflow.

Question

I am sending the json data from a python program using the below code

import json
import requests
data = {"temp_value":132}
data_json = json.dumps(data)
payload = {'json_playload': data_json}
r = requests.get('http://localhost/json1/js2.php',data=payload)

and receiving it in a php server side using the below code.

<?php
if($_GET['temp_value']) {
    $temp_value = $_GET['temp_value'];
	echo $temp_value;
	
  #  $data = array($id, $description);
   $arr=json_decode($temp_value,true);
   } else {
echo "not found";}
// Connect to MySQL
    include("dbconnect.php");
    // Prepare the SQL statement
    $SQL = "INSERT INTO test1.temperature1 (temp_value) VALUES ('$arr')";    
    // Execute SQL statement
    mysqli_query($dbh,$SQL);
	Echo "<a href=http://localhost/json1/review_data.php><center><u><b><h1>Manage values<h1><b><u></center></a>"
?>

along with the json data I have implemented like Id,time and date also gets updated in the database when i send the data.But what is happening here is like whenever i send the data from the python program it won't give any errors,when i see in the database and in the php page only 0(zero) values are inserted in both,however time and id gets updated.please someone suggest me a proper code and way.

Answer

Try this:

<?php
  $json_payload = json_decode($_GET['json_payload']);
  $temp_value   = $json_payload['temp_value'];
?>

When you do this:

r = requests.get('http://localhost/json1/js2.php',data=payload)

You are sending a get request containing a JSON string representation of your data:

'{"temp_value": 132}'

stored in the get parameter named json_payload.

Therefore, on the client side, you must retrieve the contents of the json_payload parameter and decode the JSON string therein in order to retrieve temp_value.

Alternatively, you could do this:

payload = {"temp_value":132}
r = requests.get('http://localhost/json1/js2.php',data=payload)

And leave your PHP code unmodified.