Print json in pretty format using php code - php

I have array like below.
$resultArr = array();
$resultArr['status code'] = 200;
$resultArr['result'] = "Success";
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
return $json;
This is giving result like below
"{\n \"status code\": \"200\",\n \"result\": \"Success\",\n}"
without Pretty_print the result is like below
"{\"status code\":\"200\",\"result\":\"Success\"}"
I want response to be like this
{
"status code": 200,
"result": "Success"
}
Is something like this can be done pls, I am using PHP, Running the request in postman and the response are mentioned above
Note: I need to avoid using echo, because we are using code sniffers in project, so echo is not recommended.

You used JSON_PRETTY_PRINT for beautify output purpose,
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
If you want to use it as response remove that parameter,
$json = json_encode($resultArr);
Above line should work.

First of all, remove the JSON_PRETTY_PRINT flag.
Secondly, your problem is with the backslashes (\). These are escape characters. I don't know how you are printing your json or how you are viewing it.
If I do:
echo $json;
It outputs:
{"status code":200,"result":"Success"}
The backslashes are probably added because you're doing an AJAX request. In order to solve this, you could use jQueries .parseJSON() or add dataType: "json" to your ajax request.
And if you really don't want the backslashes to be added:
$json = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
Update
It might help to output using the following header:
header('Content-Type: application/json');

1. for Output Of API You Can Use Api:
header('Content-Type: application/json');
2. Using JSON_PRETTY_PRINT
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
3. You want To Display In Chrome
https://addons.mozilla.org/en-US/firefox/addon/json-handle/?src=recommended

Related

How to remove backslashes from json response in php

I am getting json response as mentioned below:
"{\"id\":\"order_DPUVoS2YVnBccy\",\"entity\":\"order\",\"amount\":100,\"amount_paid\":0,\"amount_due\":100,\"currency\":\"INR\",\"receipt\":\"7550\",\"offer_id\":null,\"status\":\"created\",\"attempts\":0,\"notes\":[],\"created_at\":1570082483}"
I want output to be as:
{"id":"order_DPUVoS2YVnBccy","entity":"order","amount":100,"amount_paid":0,"amount_due":100,"currency":"INR","receipt":"7550","offer_id":null,"status":"created","attempts":0,"notes":[],"created_at":1570082483}
I tried using stripslashes() to remove backslashes, but its not working.
What do you mean by "not working"?
<?php
$unescapedJson = '{\"id\":\"order_DPUVoS2YVnBccy\",\"entity\":\"order\",\"amount\":100,\"amount_paid\":0,\"amount_due\":100,\"currency\":\"INR\",\"receipt\":\"7550\",\"offer_id\":null,\"status\":\"created\",\"attempts\":0,\"notes\":[],\"created_at\":1570082483}';
echo stripslashes($unescapedJson);
Output for PHP 7.1.25 - 7.4.0rc2:
{"id":"order_DPUVoS2YVnBccy","entity":"order","amount":100,"amount_paid":0,"amount_due":100,"currency":"INR","receipt":"7550","offer_id":null,"status":"created","attempts":0,"notes":[],"created_at":1570082483}
you have to do it when json decode:
$data = json_encode('yourjsonvariable'), true, JSON_UNESCAPED_SLASHES);

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

PHP grab json exchange rate value from API response

I am using currencylayer JSON API to get realtime currency conversion value - does anybody know how I could grab both the "result" value and the "quote" value from the API response below using PHP?
I am new to PHP, and I am wondering if it's possible to store it in a variable.
This is the JSON:
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"query":{
"from":"CAD",
"to":"GBP",
"amount":234
},
"info":{
"timestamp":1432829168,
"quote":0.524191
},
"result":122.660694
}
I have played around with file_get_contents("URL") but I didnt understand how to get a single value out.
Request URL looks like this:
https://apilayer.net/api/convert?access_key=...&from=CAD&to=GBP&amount=234
Thanks for the help!
Ok, lets say that json response is in a variable named $response, you must use json_decode and then do as follows:
$decoded = json_decode($response);
$result = $decoded->result;
$quote = $decoded->info->quote;
var_dump($result, $quote);
Try this
$jsonArray = file_get_contents($yourUrl);
$jsonObject = json_decode($jsonArray);
echo $jsonObject->result;
echo $jsonObject->info->quote;

Twitter typeahead displays '&amp' instead of '&'

I'm trying to display search-results with the sign & in them. But when I render from php to json & converts to &amp.
Is there anyway I can prevent that, or before I print the names in the search-bar convert it back to &?
Thanks in advance!
EDIT:
HTML JS:
{
name: 'industries',
prefetch: 'industries_json.json',
header: '<h1><strong>Industries</strong></h1>',
template: '<p>{{value}}</p>',
engine: Hogan
},
industries_json.json (Created with json_encode)
[{"id":42535,"value":"AUTOMOBILES &AMP; COMPONENTS","type":"industries"}]
php-script which ouputs json:
public function renderJSON($data){
header('Content-type: application/json');
echo json_encode($data);
}
Use html_entity_decode function like...
Code Before:
public function renderJSON($data){
header('Content-type: application/json');
echo json_encode($data);
}
output: Gives html code in string like ex: appthemes & Vantage search Suggest
Code After:
public function renderJSON($data){
header('Content-type: application/json');
$data = json_encode($data);
echo html_entity_decode( $data );
}
output: Gives html code in string like ex: appthemes & Vantage search Suggest
The issue you're facing is HTML encoding. What you want is to decode the text before sending it to the client. It is important that you only decode the text properties of the JSON object (rather than the entire JSON object itself).
Here is a reference on HTML decoding in PHP: http://php.net/manual/en/function.html-entity-decode.php
I would do it in javascript. Once you have got the JSON, just use replace function of javascript on the JSON like this:
first convert it to string by this:
var jsonString=JSON.stringify(jsonData);
then replace &amp like this.
jsonString=jsonString("&amp","&");
then again, convert it to JSON obj;
jsonObj=JSON.parse(jsonString);
now, your JSON, will have & instead of &amp.
What's next ?
Do whatever you need to do with the jsonObj

Retrieving info from JSON array with PHP

i have this public JSON https://raw.github.com/currencybot/open-exchange-rates/master/latest.json and i need to extract data from it, right now i tried something like this:
$input = file_get_contents("https://raw.github.com/currencybot/open-exchange-rates/master/latest.json");
$json = json_decode($input);
echo $json[rates]->EUR;
but i obtain a blank page, any suggestion? Thanks !! Ste
json_decode either returns an object, or an array (when you use the second param). You are trying to use both.
Try:
$json = json_decode($input);
echo $json->rates->EUR;
OR
$json = json_decode($input, true);
echo $json['rates']['EUR'];
As to the blank page, please add the following to the top of your script:
error_reporting(E_ALL);
init_set('display_errors', true);
A 500 Error indicates you are unable to resolve that url using file_get_contents.
Check here for more information.
Read the help for json_decode ... without the second parameter it returns and object not an array ...
Either :
$json = json_decode($input);
echo $json->rates->EUR;
or
$json = json_decode($input,true);
echo $json['rates']['EUR'];
Try:
$arr = json_decode($input, true);
var_dump($arr);
echo $arr['rates']['EUR'];
Further Reading:
http://de.php.net/manual/de/function.json-encode.php
For anexample with cURL and SSL read this:
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
The link looks like starting with https, while file_get_contents can't deal with SSL. My suggestion is using curl.

Categories