How to update or add value to JSON [duplicate] - php

This question already has answers here:
Is there a JSON api based CMS that is hosted locally? [closed]
(1 answer)
Update JSON value if exists otherwise add it in PHP
(2 answers)
Closed 3 years ago.
I am running an app from AndroidHive which has feed.json which the app loads the content below from.
http://api.androidhive.info/feed/feed.json and this is the post url http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
{
"feed": [{
"id": 1,
"name": "National Geographic Channel",
"image": "A URL",
"status": "Science and etc"
And Cosmos is all about making science an experience.
","
profilePic ": "
A URL ","
timeStamp ": "
1403375851930 ","
url ": null
}]
}
the above is the default content am wondering how to i add more to this content from or using a php script. I would love to know how to do it because I noticed that most application source code created in www_androidhive_info uses .json to load content which is an alternative to webview

You can use json_decode() function to convert JSON string to object, add your variable, and then conver the object back to JSON
$obj = json_decode($json, true);
$obj->feed[0]->url = "google.com"
:

Load the JSON
Decode the JSON
Add your content
Encode to JSON
Send it to your app
Code:
<?php
function failure($reason) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['failure' => $reason]);
exit;
}
// 1. Load the JSON
$content = file_get_contents('http://api.androidhive.info/feed/feed.json');
if (!$content) {
return failure('Failed to load upstream JSON');
}
// 2. Decode the JSON
$decodedContent = json_decode($content, true);
if ($decodedContent === false) {
return failure('Failed to parse upstream JSON');
} elseif (empty($decodedContent)) {
return failure('Upstream JSON empty');
}
// 3. Add your content
$decodedContent['feed'][] = [
"id": 12,
"name": "An example name",
"image": "https://example.com/test_image.jpg",
"status": "Hello!",
"profilePic": "https://example.com/test_profile_pic.jpg",
"timeStamp" => time(),
"url" => "https://example.com"
];
// 4. Encode to JSON
$responseContent = json_encode($decodedContent);
// 5. Send it to your app
echo $responseContent;

Decode the JSON and make new function for changes then encode back.
<?php
$JsonVar = file_get_contents('http://api.androidhive.info/feed/feed.json');
$myjson = json_decode($JsonVar,true);
function Changes() {
$myjson->feed[2]->name = "FeedID2";
$myjson->feed[2]->id = "2";
$myjson->feed[2]->image = "link to image.png";
$myjson->feed[2]->status = "I am here.";
$myjson->feed[2]->profilePic = "link to image.png";
$myjson->feed[2]->timeStamp = time();
$myjson->feed[2]->url = 'http://url.com';
}
json_encode(Changes());
?>

Related

Php Json Decode - Display value of second level items

I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.
You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()

Nested dictionary skips inner content while sent to a PHP webserver as JSON using Python 3.0 (Requests)

I have a large python dictionary, which is sent out as a JSON in a POST request using the py requests library to a web service which accepts incoming JSONs (XAMPP/PHP set up in localhost).
When I receive the transmitted JSON data through the POST request, PHP always gives the output as array, and not as a serialized JSON string.
Secondly, nested elements are missing from the data captured on PHP end.
I am using the following snip to do the job.
Python code :
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json', 'accept' : 'application/json'}
r = requests.post("http://localhost/test/data.php", params = (dummy_data), headers = headers)
print (r.text)
Also tried with :
headers = {'Content-Type': 'application/json'}
Both give the same output as below:
*Hello World!<br/>Printing GET array ...<br/>array(4) {
["param1"]=>
string(6) "ABCDEF"
["param2"]=>
string(1) "1"
["param3"]=>
string(19) "very_big_text_key_2"
["param4"]=>
string(6) "GHIJKL"
}
<br/>Printing POST array ...<br/>array(0) {
}*
I used json and data as parameters to "requests".
r = requests.post("http://localhost/test/data.php", json = (dummy_data), headers = headers)
and
r = requests.post("http://localhost/test/data.php", data = (dummy_data), headers = headers)
Output is as below :
*Hello World!<br/>Printing GET array ...<br/>array(0) {
}
<br/>Printing POST array ...<br/>array(0) {
}*
I am accepting data as follows in PHP code:
<?php
print "Hello World!";
echo "<br/>";
print "Printing GET array ...";
echo "<br/>";
var_dump($_GET);
echo "<br/>";
print "Printing POST array ...";
echo "<br/>";
var_dump($_POST);
?>
The inner text doesn't seem to be appearing in any of the scenarios. I have tried to implement some solutions as suggested by members of stackoverflow. But still i am facing the above mentioned issue.
The problem is now resolved. The resolution happend after consideration of the following points:
JSON passed by Python is not de-serialized by default, by PHP and has to be serialized, after inspection of "Content-type" header.
Once de-serialized, the passed JSON content was then used for further processing.
Hence the key to solve the problem was, to check the content-length, and content-type headers. If content-length was found greater than 0 and content type was application/json, the incoming JSON can be de-serialized using json_decode().
The code snips for PHP and Python, using which the following was accomplished is as below:
On the Python side:
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json'}
r = requests.post("http://localhost/test/data.php", data = json.dumps(dummy_data), headers=headers)
print (r.text)
On the PHP side:
...
if(#$_SERVER["CONTENT_LENGTH"] > 0){
$contentType = $_SERVER["CONTENT_TYPE"];
if($contentType == "application/json"){
$decoded_data = json_decode(file_get_contents("php://input"), true);
}
else{
echo "Incoming data is not a JSON!";
}
return $decoded_data;
}

How to get value from JSON php [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
This is my JSON.
{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}
My Questions are:
1. How to get OUT_STAT value?
2. How to get id_doc_proj value?
I am sorry if my questions are silly because i am new at get value from JSON.
Thanks in advance.
UPDATE
I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.
<?php
$file_path = "";
$id_project = "16";
$p_id_doc_proj = "50";
$id_doc_type = "1";
$id_user = "4";
$url = $file_path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
$ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";
$opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));
$context = stream_context_create($opts);
$arrayLog=array();
$data1 = file_get_contents($ws, false, $context);
$result = json_decode($data1, true);;
//$result = array("result" => "success");
}else{
$result = array("result" => "error");
}
echo json_encode($result);
?>
The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.
$data="{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}";
$op=json_decode($data, true);
echo $op['OUT_STAT'];
echo $op['OUT_DATA'][0]['id_doc_proj'];
http://php.net/json_deocde. it will make output as associative array. you can then use the result as you would do with an assoc array. you can also use var_dump() to introspect the structure.
you can use json_decode to convert json to array or object:
$json = '{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}';
$object = json_decode($json);
$out_stat = $object->OUT_STAT;
$id_doc_proj = $object->OUT_DATA[0]->id_doc_proj;

API Data Return to HTML

I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.

Recording a JSON POST to File Using PHP

I'm trying to record data that is being posted to my server to a text file. An example of the data that is being sent to my server is located here:
http://dev.datasift.com/docs/push/sample-output-file-based-connectors
It says on that page:
"For all file-based connectors, the payload is a JSON object containing metadata plus an array containing the JSON objects from your stream."
I have the following PHP at the location I have datasift sending data to:
<?php
$myFile = "testFile.txt";
$phpObj = json_decode($_POST['json']);
file_put_contents($myFile,$phpObj);
echo '{ "success": true }';
?>
I know data is being sent, but nothing is being recorded in my text file. It's just blank every time. I have no idea where to go from here unfortunately. Any ideas?
I think you want to get the raw content of the POST, This works for me with both POST and PUT:
$phpObj = json_decode(file_get_contents("php://input"));
$_POST contains the array from x-www-form-urlencoded content, not json.
Hope that points you in the right direction :)
Edit: #user4035 is right... your also trying to save a php object to a file... This is what i would do:
<?php
$jsonString = file_get_contents("php://input");
$myFile = "testFile.txt";
file_put_contents($myFile,$jsonString);
echo '{ "success": true }';
?>
You are trying to save an object, using file_put_contents. While data parameter this function "Can be either a string, an array or a stream resource"
http://php.net/manual/en/function.file-put-contents.php
Look at this example:
<?php
$json = '
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
';
$phpObj = json_decode($json);
var_dump($phpObj);
$myFile = "testFile.txt";
file_put_contents($myFile, $phpObj);
?>
It parses json correctly, but doesn't save anything as well, because php doesn't know, how to serialize $phpObj object.
You need to save raw JSON string:
<?php
$myFile = "testFile.txt";
file_put_contents($myFile,$_POST['json']);
echo '{ "success": true }';
?>
Then you can read the file and parse it if necessary.
I try this method and it works success. So, I share this here.
Source PHP save POST data to file
web_folder/index.php
<?php
$responseBody = file_get_contents('php://input');
$json = json_decode($responseBody);
//return data
echo json_encode($json);
//Save in json file
if($json){
$fp = fopen('results_'.time().'.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
}
?>
and run the below code in the terminal for testing, it will create a JSON file with the POST request in the same folder. (Here I used localhost) or you can test using Postman.
curl -i -X PUT -d '{"name":"codehref"}' http://localhost:8888/web_folder/index.php
To bypass the problem I used JSON.stringify.
'formSave' : function(project){
var s = {
"name": project.name,
"data": JSON.stringify(project.data)
};
$.post("sdcform/formSave/" + project.name, s);
}
The 'project' object contains the keys 'name' and 'data' and I only wanted to stringify the data part of it.
This way on the server I can do
$data = isset($_POST['data']) ? json_decode($_POST['data']): new \stdClass();
file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));
I could store it directly to the file and save both conversion but I wanted to prettyfy it!
Note: Yes I know! Do not access $_POST directly.

Categories