how to remove back slashes from json output in php - php

The code I have used:
$val = json_encode(array("test"=>test1,"test2" =>test,"description" => description));
return $val;
The result im getting
{\"test\":\"test1\",\"test2\":\"test\",\"description\":\"description\"}
I need this to fix api

Try with stripslashes()
echo stripslashes('{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}');
stripslashes()

Tried this.
$val = json_encode(array(
"test"=>'test1',
"test2" =>'test',
"description" => 'description'
));
$data = json_decode($val, true, JSON_UNESCAPED_SLASHES);
return $data;
This is the result I received.

In php "stripslashes" function is present using that you can remove backslash.
Link for more details.
Example:
echo $strnew = stripslashes('{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}');

Use stripslashes() And read stripslashes
<?php
$srt="'{\"test\":{\"test1\":{\"test1\":[{\"test2\":\"1\",\"test3\": \"foo\",\"test4\":\"bar\",\"test5\":\"test7\"}]}}}'
";
echo stripslashes($srt);
OUTPUT
'{"test":{"test1":{"test1":[{"test2":"1","test3":
"foo","test4":"bar","test5":"test7"}]}}}'

you can use JSON_UNESCAPED_SLASHES
json_encode($yourjson, JSON_UNESCAPED_SLASHES);

Use string find and replace function
$str="{"test":{"test1":{"test1":[{"test2":"1","test3": "foo","test4":"bar","test5":"test7"}]}}}";
str_replace("\'","'",$str);

Try the following code. It works perfectly fine for me $cha a string with backslashes
$cha = "{\"ashen\":\"143\"}";
$chachi = json_decode($cha,JSON_UNESCAPED_SLASHES);
return $chachi['ashen'];
output: 143

Actually, only Khachornchit Songsaen answer is correct.
stripslashes does not work on unescaping escaped " in json encoded strings inside another json.
es.
{ "key1" :"value1", "key2": "{\"key\":\"Text \\\"text\\\" text\"}" }
using json_decode($var, true, JSON_UNESCAPED_SLASHES) does the job correctly.

this is the right method when your result is coming in slashes do this
$data = [
"message" => '',
"data" => $product
];
$response[] = $data;
return $response;
do this it's really work because after 5 day i fund this solution or it is right .

I was facing same issue, it is resolved by using echo and exit;
$response = json_encode(array("test"=>"test1","test2"
=>"test","description" => "description"));
echo $response;
exit;

Related

php: wanted to replace '\\\/' from string

I wanted to replace en/us with es/es:
<?php
$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$json = json_encode($str);
$str = str_replace('en\/us', 'es\/es', $json);
echo $str;
You need to 'double escape' the backslash, like so:
<?php
$str = array('url'=>'www.domain.com/data/en/us/data.gif');
$json = json_encode($str);
$str = str_replace('en\\/us', 'es\\/es', $json);
echo $str;
See http://php.net/manual/en/language.types.string.php (section 'Single quoted').
Would be easier to escape the string BEFORE feeding it to json_encode, but I'm assuming this is a test case and the data you want to replace in is already JSON.
JSON is a useful format for moving data between systems. Converting data to JSON and then trying to manipulate it without parsing it first is almost always a terrible (overly complicated and error prone) idea.
Do the replacement before you convert it to JSON.
<?php
function replace_country($value) {
echo $value;
echo "\n";
return str_replace('en\/us', 'es\/es', $value);
}
$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str = array_map("replace_country", $str);
$json = json_encode($str);
echo $json;
Try this
$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str['url']=str_replace('en\/us', 'es\/es', $str['url']);
$json = json_encode($str);
It produce out put as
It will work for you.

how to decode url which is encoded by http_build_query

i want to pass array in url, so i have encoded using http_build_query
$filterArray = array('OrderNo'=>$_REQUEST['txtorderno'],
'StoreName'=>$_REQUEST['txtstorename'],
'PartyCode'=>$_REQUEST['txtpartycode'],
'fromdate'=>$_REQUEST['txtfromdate'],
'todate'=>$_REQUEST['txttodate'],
'minamount'=>$_REQUEST['txtminamount'],
'maxamount'=>$_REQUEST['txtmaxamount']);
$data = array('DistributorId' => $_GET['DistributorId'], 'StoreId' => $_GET['StoreId'],'filterArray' => http_build_query($filterArray));
finally my URL is generated like this
http://localhost/test/orderdetails.php?DistributorId=&StoreId=&filterArray=OrderNo%3D1%26StoreName%3D2%26PartyCode%3D3%26fromdate%3D04%252F26%252F2017%26todate%3D04%252F27%252F2017%26minamount%3D111%26maxamount%3D222
now how do i get all the parameters from url ??
i tried to print filterArray parameter like
echo "<pre>";
$arr = (urldecode($_GET['filterArray']));
var_dump($arr);
it prints
string(99) "OrderNo=1&StoreName=2&PartyCode=3&fromdate=04/26/2017&todate=04/27/2017&minamount=111&maxamount=222"
You can use parse_str[1]:
<?php
$inputStr = 'OrderNo=1&StoreName=2&PartyCode=3&fromdate=04/26/2017&todate=04/27/2017&minamount=111&maxamount=222';
parse_str($inputStr, $output);
var_dump($output);
?>
Example: https://3v4l.org/toiKf
[1]: http://php.net/manual/de/function.parse-str.php

PHP: json_decode not working

This does not work:
$jsonDecode = json_decode($jsonData, TRUE);
However if I copy the string from $jsonData and put it inside the decode function manually it does work.
This works:
$jsonDecode = json_decode('{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}', TRUE);
I did output $jsonData copied it and put in like above in the decode function. Then it worked. However if I put $jsonData directly in the decode function it does not.
var_dump($jsonData) shows:
string(144) "{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}"
The $jsonData comes from a encrypted $_GET variable. To encrypt it I use this:
$key = "SOME KEY";
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB, $iv);
$iv = rawurlencode(base64_encode($iv));
$enc = rawurlencode(base64_encode($enc));
//To Decrypt
$iv = base64_decode(rawurldecode($_GET['i']));
$enc = base64_decode(rawurldecode($_GET['e']));
$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB, $iv);
some time there is issue of html entities, for example \" it will represent like this \&quot, so you must need to parse the html entites to real text, that you can do using
html_entity_decode()
method of php.
$jsonData = stripslashes(html_entity_decode($jsonData));
$k=json_decode($jsonData,true);
print_r($k);
You have to use preg_replace for avoiding the null results from json_decode
here is the example code
$json_string = stripslashes(html_entity_decode($json_string));
$bookingdata = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
Most likely you need to strip off the padding from your decrypted data. There are 124 visible characters in your string but var_dump reports 144. Which means 20 characters of padding needs to be removed (a series of "\0" bytes at the end of your string).
Probably that's 4 "\0" bytes at the end of a block + an empty 16-bytes block (to mark the end of the data).
How are you currently decrypting/encrypting your string?
Edit:
You need to add this to trim the zero bytes at the end of the string:
$jsonData = rtrim($jsonData, "\0");
Judging from the other comments, you could use,
$jsonDecode = json_decode(trim($jsonData), TRUE);
While moving on php 7.1 I encountered with json_decode error number 4 (json syntex error). None of the above solution on this page worked for me.
After doing some more searching i found solution at https://stackoverflow.com/a/15423899/1545384 and its working for me.
//Remove UTF8 Bom
function remove_utf8_bom($text)
{
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
Be sure to set header to JSON
header('Content-type: application/json;');
str_replace("\t", " ", str_replace("\n", " ", $string))
because json_decode does not work with special characters. And no error will be displayed. Make sure you remove tab spaces and new lines.
Depending on the source you get your data, you might need also:
stripslashes(html_entity_decode($string))
Works for me:
<?php
$sql = <<<EOT
SELECT *
FROM `students`;
EOT;
$string = '{ "query" : "' . str_replace("\t", " ", str_replace("\n", " ", $sql)).'" }';
print_r(json_decode($string));
?>
output:
stdClass Object
(
[query] => SELECT * FROM `students`;
)
I had problem that json_decode did not work, solution was to change string encoding to utf-8. This is important in case you have non-latin characters.
Interestingly mcrypt_decrypt seem to add control characters other than \0 at the end of the resulting text because of its padding algorithm. Therefore instead of rtrim($jsonData, "\0")
it is recommended to use
preg_replace( "/\p{Cc}*$/u", "", $data)
on the result $data of mcrypt_decrypt. json_decode will work if all trailing control characters are removed. Pl refer to the comment by Peter Bailey at http://php.net/manual/en/function.mdecrypt-generic.php .
USE THIS CODE
<?php
$json = preg_replace('/[[:cntrl:]]/', '', $json_data);
$json_array = json_decode($json, true);
echo json_last_error();
echo json_last_error_msg();
print_r($json_array);
?>
Make sure your JSON is actually valid. For some reason I was convinced that this was valid JSON:
{ type: "block" }
While it is not. Point being, make sure to validate your string with a linter if you find json_decode not te be working.
Try the JSON validator.
The problem in my case was it used ' not ", so I had to replace it to make it working.
In notepad+ I changed encoding of json file on: "UTF-8 without BOM".
JSON started to work
TL;DR Be sure that your JSON not containing comments :)
I've taken a JSON structure from API reference and tested request using Postman. I've just copy-pasted the JSON and didn't pay attention that there was a comment inside it:
...
"payMethod": {
"type": "PBL" //or "CARD_TOKEN", "INSTALLMENTS"
},
...
Of course after deletion the comment json_decode() started working like a charm :)
Use following function:
If JSON_ERROR_UTF8 occurred :
$encoded = json_encode( utf_convert( $responseForJS ) );
Below function is used to encode Array data recursively
/* Use it for json_encode some corrupt UTF-8 chars
* useful for = malformed utf-8 characters possibly incorrectly encoded by json_encode
*/
function utf_convert( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}
Maybe it helps someone, check in your json string if you have any NULL values, json_decode will not work if a NULL is present as a value.
This super basic function may help you. I made the NULL in an array just in case I need to add more stuff in the future.
function jsonValueFix($json){
$json = str_replace( array('NULL'),'""',$json );
return $json;
}
I just used json_decode twice and it worked for me
$response = json_decode($apiResponse, true);
$response = json_decode($response, true);

Return JSON inside data[] php

I'm using the following to pull some data fro facebook:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
echo $tagData;
This produces e.g.:
{"data":
[
{"name":"Jonathan Montiel","id":"28125695"},
{"name":"Jackson C. Gomes","id":"51300292"}
],
"paging":{"next":"https:\/\/graph.facebook.com\/123456789\/friends?access_token=5148835fe&limit=5000&offset=5000&__after_id=100060104"}}
QUESTION How I can just return ONLY what's inside the [...] including the [ ]?
Desired result:
[
{"name":"Jonathan James","id":"28125695"},
{"name":"Jackson C. Cliveden","id":"51300292"}
]
Try this:
$tagData = json_decode( $tagData, true );
$data = $tagData['data'];
echo json_encode( $data );
This basically converts the JSON to an array, extracts the desired part and returns this again as JSON-encoded.
EDIT
Example Fiddle
json_decode and reencode with json_encode necessary part of the response. Following is going to work for you:
$tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token);
$tagData = json_decode($tagData);
echo json_encode($tagData->data);
Thanks to Sirco for the inspiration, this works although how its different to answer given I have no clue!
$tagData = json_decode(file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token), true );
$data = $tagData['data'];
echo json_encode( $data );

How to include a php variable in json and pass to ajax

My Code
var json = xmlhttp.responseText; //ajax response from my php file
obj = JSON.parse(json);
alert(obj.result);
And in my php code
$result = 'Hello';
echo '{
"result":"$result",
"count":3
}';
The problem is: when I alert obj.result, it shows "$result", instead of showing Hello.
How can I solve this?
The basic problem with your example is that $result is wrapped in single-quotes. So the first solution is to unwrap it, eg:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
But this is still not "good enough", as it is always possible that $result could contain a " character itself, resulting in, for example, {"result":""","count":3}, which is still invalid json. The solution is to escape the $result before it is inserted into the json.
This is actually very straightforward, using the json_encode() function:
$result = 'Hello';
echo '{
"result":'.json_encode($result).',
"count":3
}';
or, even better, we can have PHP do the entirety of the json encoding itself, by passing in a whole array instead of just $result:
$result = 'Hello';
echo json_encode(array(
'result' => $result,
'count' => 3
));
You should use json_encode to encode the data properly:
$data = array(
"result" => $result,
"count" => 3
);
echo json_encode($data);
You're using single quotes in your echo, therefore no string interpolation is happening
use json_encode()
$arr = array(
"result" => $result,
"count" => 3
);
echo json_encode($arr);
As a bonus, json_encode will properly encode your response!
Try:
$result = 'Hello';
echo '{
"result":"'.$result.'",
"count":3
}';
$result = 'Hello';
$json_array=array(
"result"=>$result,
"count"=>3
)
echo json_encode($json_array);
That's all.

Categories