php addslashes becomes illegal token in javascript - php

i tried using jquery ajax call, everything works fine until i tried to escape the json string using addslashes on the the server side i get the follow error : unexpected token illegal. here is my json string i cant find any problems in it
[{\"shortlist\":{\"id\":\"46\",\"application_id\":\"3\",\"created\":\"2012-04-
22\",\"modified\":\"2012-04-22\"},\"application\":
{\"id\":\"3\",\"admissionsession_id\":\"0\",\"school_id\":\"\",\"surname\":\"oni\",\"
other_names\":\"oluwafemi timothy Toluwalope\",\"date_of_birth\":\"0000-00-
00\",\"created\":\"2012-04-15\",\"modified\":\"2012-04-15\"}}]
if i remove the addslahes from the php json string it works fine. am scared of leaving my string unescaped tho.

add your data structure in an array:
$data = array('shortlist' => array('id' => 46, ....
then use:
$json = json_encode($data);
echo $json;

Related

Storing JSON as a string in JSON using PHP

For testing purposes, I wish to use Ajax to request some JSON from the server. From the Ajax client's perspective, the JSON should look like:
json=[
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'}
];
Note that jsonstring is not JSON, but a string, and $.getJSON() should not parse it into an object.
My attempt is below, however, I get error Parse error: syntax error, unexpected ',' in /var/www/test/src/classes/Ajax.php on line 13.
How should this be performed?
$content=file_get_contents('../buffer.json',true); //Line 13
$buffer=$content?json_decode($content):[];
$json=json_encode(['a'=>1,'b'=>2,'c'=>3]);
$buffer[]=[
'source'=>'pa',
'jsonstring'=>'"'.$json.'"'
];
$buffer=json_encode($buffer);
file_put_contents('../buffer.json',$buffer);
header('Content-Type: application/json');
echo($buffer);
buffer.json output is shown below:
[{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""},{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""}]
Have you tried removing the extra quotes from 'jsonstring'=>'"'.$json.'"'? If you json_encode it (which it looks like you do), then it is already a string. I think it should be 'jsonstring' => $json.

Having trouble while trying to send URL via JSON in PHP

I am working on web services of Android application in PHP. I am trying to send URL with other data in JSON. But the data sent by URL shows unwanted slashes (//) in the URL.
Here is the code I am using:
if(isset($_POST['category_id'])):
$result=$db->sub_category($_POST['category_id']);
if($result):
$msg="Success";
$arr = array();
while($row=mysql_fetch_array($result)):
$arr['response'][] = array('category' => $row['category'], 'image' => "http://intelmobizsolution.com/Iphone/upload/iphone/".$row['image'], 'msg'=>$msg,'status'=>true);
endwhile;
$abc=json_encode($arr);
echo json_encode($arr);
endif;
endif;
But the result shows like this:
{"response":[{"category":"Administrative Support2","image":"http:\/\/intelmobizsolution.com\/Iphone\/upload\/iphone\/27792582102banner_02.jpg","msg":"Success","status":true}]}
How can I send a URL with JSON in the format I want?
The best approach is to accept the slashes. They do absolutely not harm. It is perfectly acceptable to have them escaped in JSON strings.
If you really want to get rid of them, then you can use:
json_encode($arr, JSON_UNESCAPED_SLASHES);
… but if your data ever includes the string </script> and you output the JSON into some JavaScript in an HTML document, then you'll break your script.
In PHP > 5.4 you can use
json_encode($arr, JSON_UNESCAPED_SLASHES);
http://php.net/manual/en/function.json-encode.php

Json encode array with php - array() becomes "Array{...}" not "[...]"

I'm trying to encode a response array as json and it has worked until now.
$response = array();
$response['icons']= $icons_arr;
$response['message']= $msg;
echo json_encode( $response );
The result is
Array{"icons":["{\r\n\t\t\t\t\t\"icon_web_id\": \t\t\t\"0 ...
Javascript throws an error as it can't parse the "Array" word. I suspect the JQuery function $.parseJSON() expects a {} or a [].
What am I doing wrong here? Why won't json_encode() function properly?
Bonus question: what is causing all these \t\t\t\t's to occur?
Some other piece of code is producing the 'Array' output before the json string is output, you can prove this by changing the output line to
echo "json_encode returned ".json_encode( $response );
Check your code for other echo statements.
Regarding your Bonus question:
The \t is a tab in PHP. Your code may contain tabs instead of spaces somewhere, which could be rendered as multiple \t's.

PHP JSON Parser v.s. Javascript JSON Parser

I have an array via json_encode of PHP serialize:
json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
// output json: {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
I tried to decode in Javascript:
JSON.parse('{"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}');
Then I don't understand why do I get an error "Uncaught SyntaxError: Unexpected token w" ??
Is PHP and Javascript JSON parser difference?
The problem is because you're using JSON.parse() and enclosing your JSON string in single quotes.
So your escaped regex string gets unescaped in the interpretation of the outer string-literal (single-quoted), and then gets mixed up in the interpretation of the value of the string pattern (double-quoted), ultimately causing JavaScript to choke trying to decipher "\w".
The following example, mimicking PHP rendering the JSON verbatim to a declaration, works fine in a JS console:
var json = {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
If you want to use JSON.parse, you have to first double-escape your JSON string in PHP
$json = json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
$json = str_replace('\', '\\', $json);
// output json: {"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}
Then, in JS:
var json = JSON.parse('{"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}')

Why is json_encode adding backslashes?

I've been using json_encode for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.
I have the following code:
print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON
This gives me the following results:
// print_r result
Array
(
[logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
[img_id] => 54
[feedback] => Array
(
[message] => File uploaded
[success] => 1
)
)
// Echo result
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Can anyone tell me why json_encode adds slashes?
update
#Quentin said that something is happening between json_encode and .parseJSON and he's right.
Doing a alert(data.toSource()); gives me the dollowing result:
({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})
And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from.
Could it be that the Plupload bind does something to my returned data?
This is my js script:
uploader.bind('FileUploaded', function(up, file, data) {
alert(data.toSource());
$('#' + file.id + " b").html("100%");
});
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.
Here is what was happening. If you do:
$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);
The result is:
["{\"test\":\"2\"}","{\"test\":\"four\"}"]
So, what you actually need to do is:
$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);
And this will return
[{"test":"2"},{"test":"four"}]
Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/" and "\/" are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\".".
This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]
Make sure your php script has the right header or it will add the slashes
header('Content-Type: application/json');
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
json_encode will always add slashes.
Check some examples on the manual HERE
This is because if there are some characters which needs to escaped then they will create problem.
To use the json please Parse your json to ensure that the slashes are removed
Well whether or not you remove slashesthe json will be parsed without any problem by eval.
<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>
This is my code and i m able to parse the JSON.
Check your code May be you are missing something while parsing the JSON

Categories