Handling nested JSON POST requests in PHP - php

I am trying to have a python client send a post request which contains nested JSON like such
{"nested":{"field1":"response1", "field2":"response2"}}
My python code is here
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url="http://localhost/api/vscore.php"
post_fields={"nested":{"field1":"response1", "field2":"response2"}}
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
PHP code:
print_r($_POST["nested"]);
returns
{'field2': 'response2', 'field1': 'response1'}
but when I try to access "field1" with $_POST["nested"]["field1"], it returns this:
{
instead of returning "response1". How can I get my code to return fields in nested JSON?

If request is in json form then, you should json_decode it first and then try to access. nested key should be accessed as:
$nested = json_decode($_POST["nested"], true);
$field = $nested["field1"];

Related

Get the value from Rest post API

Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation

sending the json data from python to php

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.
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.
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)
print(r.url)//http://localhost/json1/js2.php
Json data is not passed in to php.Check your python code
payload = {'key1': 'value1', 'key2[]': ['value2', 'value3']}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
Result:
http://httpbin.org/get?key1=value1&key2%5B%5D=value2&key2%5B%5D=value3
You have to use like
payload = {"temp_value":132}

How to load json data defined in a JavaScript file to a php variable

I've some JSON data in a javascript file
Data is build using javascript object literal notation;
var CMS = window.CMS = window.CMS || {};
CMS.Data = window.CMS.Data = window.CMS.Data || {};
CMS.Data['LANGUAGES'] = [
{id:"chi", value:"Chinese"},
{id:"spa", value:"Spanish"},
{id:'eng', value:"English"},
{id:"hin", value:"Hindi"},
];
CMS.Data['AGE_RANGE'] = [{id:'18', value:"18"}, {id:'25', value:"25"}, {id:'30', value:"30"}, {id:'35', value:"35"}, {id:'40', value:"40"}, {id:'50', value:"50"}, {id:'60', value:"60"}, {id:'70', value:"70"}, {id:'80', value:"80"}, {id:'90', value:"90"}, {id:'100', value:"100"}];
CMS.Data['HEIGHT_RANGE'] = [{id:'140-150', value:"140-150"}, {id:'150-160', value:"150-160"}, {id:'160-170', value:"160-170"}, {id:'180-190', value:"180-190"}];
Complete data is available at https://gist.github.com/mithunqb/675613fe985fe2afbbcf
I need to make it available in PHP array.
I cannot simply load the content and apply json_decode
$json_string = file_get_contents('data.json');
$json_array = json_decode($json_string, true);
As the content inside the json file is not actually a valid JSON string, the above operation will result NULL;
How can I do this?
If the JSON string is not valid then there is no way to convert it to PHP array. Not a chance at any circumstances. It's obvious.
You must provide a valid JSON string.

Instagram Real time API - PHP - Unable to get POST Update

I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.

Json problem in flickr

I have this json but I have no idea how to get 7796249#N02
a:2:{s:4:"user";a:3:{s:2:"id";s:11:"7796249#N02";s:4:"nsid";s:11:"7796249#N02";s:8:"username";a:1:{s:8:"_content";s:9:"ilhan.z.y";}}s:4:"stat";s:2:"ok";}
That is a serialized PHP array, not JSON. Use:
$array = unserialize('that response goes in here');
What language are you using? In Groovy, for example, you would do something like this:
import groovyx.net.http.*
#Grab(group='org.codehaus.groovy.modules.http-builder',
module='http-builder', version='0.5.0' )
def http = new HTTPBuilder( 'http://twitter.com/statuses/' )
http.get( path: 'user_timeline.json',
query: [id:'httpbuilder', count:5] ) { resp, json ->
println resp.status
json.each { // iterate over JSON 'status' object in the response:
println it.created_at
println ' ' + it.text
}
}
Edit after PHP tag added:
I'm not a PHP guy, but it looks like json_decode is what you need to use.

Categories