How to remove backslashes from json response in php - 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);

Related

Print json in pretty format using php code

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

How to JSON encode an array with French accents?

There are many threads about this but none of them helped me solve this problem.
$array=array(
"dépendre"=>"to depend",
"dire"=>"to say",
"distraire"=>"distracted",
"être"=>"to be (being)",
);
Gets encoded like this with json_encode :
"d\u00e9pendre":"to depend","dire":"to say","distraire":"distracted","\u00eatre":"to be (being)"
So far I have tried this:
array_walk_recursive($array,function($value,$key) {
$key = urlencode(utf8_decode($key));
});
Try this,
json_encode($array, JSON_UNESCAPED_UNICODE);
You should get this result;
{
"dépendre":"to depend",
"dire":"to say",
"distraire":"distracted",
"être":"to be (being)"
}
Please check the result from the following code:
<?php
$x=array(
"dépendre"=>"to depend",
"dire"=>"to say",
"distraire"=>"distracted",
"être"=>"to be (being)",
);
$encoded = json_encode($x);
var_dump($x);
var_dump(json_decode($encoded, true));
The string you get in your question is a correctly escaped JSON and could be successfully decoded.

How to filter the follow JSON using PHP?

I am performing a query against a Payment Gateway and this is part of a JSON I am receiving as reply:
"//{\"COLUMNS\":[\"TR_ID\",\"INV_ID_EXT\",\"CUST_ID_EXT\",\"MERCH_ID\", ... ,null,\"510510\",1,24]]}"
How can I delete from the string the "\" to get transform in a real JSON?
What I did so far:
echo $JSON2 = str_replace("//","",$theString);
I get this:
"{\"COLUMNS\":[\"TR_ID\", ...
When I try str_replace("\\","",$JSON2); I still have the "{\"COLUMNS\":[\"TR_ID\", ...
For some reason I am able to remove the // but not \ .
How could I remove the \ from this string without loop character by character?
Have you tried like this using str_replace and stripslashes? see here https://eval.in/836989
<?php
$string="//{\"COLUMNS\":[\"TR_ID\",\"INV_ID_EXT\",\"CUST_ID_EXT\",\"MERCH_ID\", ... ,null,\"510510\",1,24]]}";
echo stripslashes(str_replace('//','',$string));
?>
N.B: This will remove // and \ characters from your string but still it's not a valid json. A valid json will be like this, so in that case you've to also remove the last ] and ... from the string
{
"COLUMNS": ["TR_ID", "INV_ID_EXT", "CUST_ID_EXT", "MERCH_ID", null, "510510", 1, 24]
}
For that : https://eval.in/837000
For Magic Quotes issue : PHP stripslashes problem
try using the stripslashes() function
echo stripslashes($JSON2);
the black slashes works as an escape i belive

JSON not decoding in php

i am using json decoding function in php to decode this
{"department_id":"3123a79d-9e33-543f-c9be-4cc7ff79982c",
"ug_id":"217a783c-7970-8d92-6c99-5225a3ec533a",
"pg_id":"90da4eb5-6b75-44b0-2ce0-5226c8f60f8e",
"staff_id":"1e6364a3-0b3d-6384-a6c2-5225bd41c7fd",
"from_date":"date_start",
"to_date":"date_end"}
I have use json_decode($str) and json_decode($str,true) both, but i am getting null output. Please help me if possible.
Here is my complete code
$query='SELECT params FROM userreports WHERE id=\''.$_REQUEST['record'].'\'';
$query_exe=$db->query($query);
$res=$db->fetchByAssoc($query_exe);
$json=$res['params'];
$arr=json_decode($json,true);
echo '<pre>';
print_r($arr) ;exit;
Try following code it is working fine:
<?php
$str = '{"department_id":"3123a79d-9e33-543f-c9be-4cc7ff79982c",
"ug_id":"217a783c-7970-8d92-6c99-5225a3ec533a",
"pg_id":"90da4eb5-6b75-44b0-2ce0-5226c8f60f8e",
"staff_id":"1e6364a3-0b3d-6384-a6c2-5225bd41c7fd",
"from_date":"date_start",
"to_date":"date_end"}';
$arrStr = json_decode($str);
print_r($arrStr);
?>

PHP json_decode() returns NULL with seemingly valid JSON?

I have this JSON object stored on a plain text file:
{
"MySQL": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"DatabaseName": "(dbname)"
},
"Ftp": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"RootFolder": "(rf)"
},
"BasePath": "../../bin/",
"NotesAppPath": "notas",
"SearchAppPath": "buscar",
"BaseUrl": "http:\/\/montemaiztusitio.com.ar",
"InitialExtensions": [
"nem.mysqlhandler",
"nem.string",
"nem.colour",
"nem.filesystem",
"nem.rss",
"nem.date",
"nem.template",
"nem.media",
"nem.measuring",
"nem.weather",
"nem.currency"
],
"MediaPath": "media",
"MediaGalleriesTable": "journal_media_galleries",
"MediaTable": "journal_media",
"Journal": {
"AllowedAdFileFormats": [
"flv:1",
"jpg:2",
"gif:3",
"png:4",
"swf:5"
],
"AdColumnId": "3",
"RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
"FrontendLayout": "Flat",
"AdPath": "ad",
"SiteTitle": "Monte Maíz: Tu Sitio",
"GlobalSiteDescription": "Periódico local de Monte Maíz.",
"MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
"TemplatePath": "templates",
"WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
"WeatherMeasureType": "1",
"CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
"TimesSingular": "vez",
"TimesPlural": "veces"
}
}
When I try to decode it with json_decode(), it returns NULL. Why?
The file is readable (I tried echoing file_get_contents() and it worked ok).
I've tested JSON against http://jsonlint.com/ and it's perfectly valid.
What's wrong here?
This worked for me
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
It could be the encoding of the special characters. You could ask json_last_error() to get definite information.
You could try with it.
json_decode(stripslashes($_POST['data']))
If you check the the request in chrome you will see that the JSON is text, so there has been blank code added to the JSON.
You can clear it by using
$k=preg_replace('/\s+/', '',$k);
Then you can use:
json_decode($k)
print_r will then show the array.
Maybe some hidden characters are messing with your json, try this:
$json = utf8_encode($yourString);
$data = json_decode($json);
I had the same problem and I solved it simply by replacing the quote character before decode.
$json = str_replace('"', '"', $json);
$object = json_decode($json);
My JSON value was generated by JSON.stringify function.
For me the php function stripslashes() works when receiving json from javascript. When receiving json from python, the second optional parameter to the json_decode call does the trick since the array is associative. Workes for me like a charm.
$json = stripslashes($json); //add this line if json from javascript
$edit = json_decode($json, true); //adding parameter true if json from python
this help you to understand what is the type of error
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>
This error means that your JSON string is not valid JSON!
Enable throwing exceptions when an error happens and PHP will throw an exception with the reason for why it failed.
Use this:
$json = json_decode($string, null, 512, JSON_THROW_ON_ERROR);
Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.
If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:
$jsonData = trim($jsonData);
The most important thing to remember, when you get a NULL result from JSON data that is valid is to use the following command:
json_last_error_msg();
Ie.
var_dump(json_last_error_msg());
string(53) "Control character error, possibly incorrectly encoded"
You then fix that with:
$new_json = preg_replace('/[[:cntrl:]]/', '', $json);
Here is how I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding, mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode() to return null
In my case , i was facing the same issue , but it was caused by slashes inside the json string so using
json_decode(stripslashes($YourJsonString))
OR
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $YourJsonString), true );
If the above doesnt work, first replace the quotes from html quote , this might be happening if you are sending data from javascript to php
$YourJsonString = stripslashes($YourJsonString);
$YourJsonString = str_replace('"', '"', $YourJsonString);
$YourJsonString = str_replace('["', '[', $YourJsonString);
$YourJsonString = str_replace('"]', ']', $YourJsonString);
$YourJsonString = str_replace('"{', '{', $YourJsonString);
$YourJsonString = str_replace('}"', '}', $YourJsonString);
$YourJsonObject = json_decode($YourJsonString);
Will solve it,
It's probably BOM, as others have mentioned. You can try this:
// BOM (Byte Order Mark) issue, needs removing to decode
$bom = pack('H*','EFBBBF');
$response = preg_replace("/^$bom/", '', $response);
unset($tmp_bom);
$response = json_decode($response);
This is a known bug with some SDKs, such as Authorize.NET
If you are getting json from database, put
mysqli_set_charset($con, "utf8");
after defining connection link $con
Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
So, html_entity_decode() worked for me. Please try this.
$input = file_get_contents("php://input");
$input = html_entity_decode($input);
$event_json = json_decode($input,true);
It took me like an hour to figure it out, but trailing commas (which work in JavaScript) fail in PHP.
This is what fixed it for me:
str_replace([PHP_EOL, ",}"], ["", "}"], $JSON);
I recommend creating a .json file (ex: config.json).
Then paste all of your json object and format it. And thus you will be able to remove all of that things that is breaking your json-object, and get clean copy-paste json-object.
I also face the same issue...
I fix the following steps... 1) I print that variable in browser 2) Validate that variable data by freeformatter 3) copy/refer that data in further processing
after that, I didn't get any issue.
This happen because you use (') insted {") in your value or key.
Here is wrong format.
{'name':'ichsan'}
Thats will be return NULL if you decode them.
You should pass the json request like this.
{"name":"ichsan"}
I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):
print_r(file_get_contents($url));
Turned out there was a trailing <pre> tag.
you should ensure these points
1. your json string dont have any unknowns characters
2. json string can view from online json viewer (you can search on google as online viewer or parser for json) it should view without any error
3. your string dont have html entities it should be plain text/string
for explanation of point 3
$html_product_sizes_json=htmlentities($html);
$ProductSizesArr = json_decode($html_product_sizes_json,true);
to (remove htmlentities() function )
$html_product_sizes_json=$html;
$ProductSizesArr = json_decode($html_product_sizes_json,true);
For my case, it's because of the single quote in JSON string.
JSON format only accepts double-quotes for keys and string values.
Example:
$jsonString = '{\'hello\': \'PHP\'}'; // valid value should be '{"hello": "PHP"}'
$json = json_decode($jsonString);
print $json; // null
I got this confused because of Javascript syntax. In Javascript, of course, we can do like this:
let json = {
hello: 'PHP' // no quote for key, single quote for string value
}
// OR:
json = {
'hello': 'PHP' // single quote for key and value
}
but later when convert those objects to JSON string:
JSON.stringify(json); // "{"hello":"PHP"}"
Before applying PHP related solutions, validate your JSON format. Maybe that is the problem. Try this online JSON format validator.
For me, I had to turn off the error_reporting, to get json_decode() working correctly. It sounds weird, but true in my case. Because there is some notice printed between the JSON string that I am trying to decode.
I had exactly the same problem
But it was fixed with this code
$zip = file_get_contents($file);
$zip = json_decode(stripslashes($zip), true);
I had the same issue and none of the answers helped me.
One of the variables in my JSON object had the value Andaman & Nicobar. I removed this & and my code worked perfectly.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>

Categories