json_encode with double quotes passed into JSON.parse - javascript

I have seen that this question has been asked too many times over the years. Still can't refrain from asking if anything was improved during this time.
Currently, I have PHP code:
$jsonData = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
and then JS (Angular to be specific) comes into play:
var decoded = angular.fromJson('<?php echo $jsonData ; ?>');
The flags above do a very good job of keeping some of the issues at bay. However, given the example:
$data = ["name" => "Name \"Nickname\" Surname"];
JSON fails to parse. If I wrap the data with addslashes(), it does work, but then:
$data = ["name" => "Name 'Nickname' Surname"];
This fails.
Since the structure $data is highly unpredictable, and usually is 4-5 levels deep, my solution was:
array_walk_recursive($data, function(&$item, $key){
$item = str_replace('"', '\"', $item);
});
This works, however, I am looking for some more knowledgeable source. I've read some other SO questions where people escape not only double quotes but line feeds, carriage return and backslashes as well.
The last thing I need is to fall into edge case trap :)
Any hints for me?

Since json can be used directly as an object literal in javascript, you could use it like this:
var decoded = <?php echo $jsonData ; ?>;
thus eliminating the need to do any further parsing to avoid issues with ' or \ characters within the text. the json_encode should already be taking care of " charaters.

Related

Cannot echo strings with "" , '' and /n from PHP to JavaScript

I tried to show a description from the YouTube API to p element but it's not working. I think the problem is with the quotes, single quote and new line; ie. "" , '' and \n.
This is the description text:
Another contestant attempts to overcome 'Head Case'! Will Daniel be able to "master" his fear of the unknown and be able to carry on singing?\n\nSubscribe for more awesome clips!\n\nSubscribe now!
$description = $vid["items"][0]["snippet"]["description"];
echo "<script>$('.pClass:nth-of-type(4)').text($description);</script>";
Note that it's working like this: $('.pClass:nth-of-type(4)').text('test');, but it's not working when read from the API.
You're outputting data to JavaScript, so you need to escape it in a way that will be safe for JavaScript to consume. Since JSON is a subset of JavaScript, you can use json_encode() for this purpose.
You should also avoid outputting JS in a double-quoted string; you can have problems with JS values being interpreted as PHP variables.
<?php
$description = json_encode($vid["items"][0]["snippet"]["description"]);
?>
<script>
$('.pClass:nth-of-type(4)').text(<?=$description?>);
</script>

How to serialize a PHP object into a JavaScript object (Not JSON)

I've used json_encode($array); to convert an array to a json.
[{"x":1418736600,"y":"82.2"},{"x":1418736900,"y":"82.2"}]
But what I really need is a JavaScript object like the following:
[{x:1418736600,y:"82.2"},{x:1418736900,y:"82.2"}]
To make it short I would like a JSON without quoting the keys, but it would be preferable avoiding parsing what json_encode outputs and using a more straightforward way instead.
Is it possible to do this in PHP?
Other than making the payload very slightly smaller, there's no need to do this. The output of json_encode is valid JavaScript code, if used where a value is expected, e.g.:
var x = <?php echo json_encode($array); ?>;
The quoted property keys are valid JavaScript. JSON as a whole is, in fact, a subset of JavaScript literal syntax.
You could throw a regular expression at the result. It can probably never be perfect (JSON, like HTML, can't be correctly parsed with a single regular expression), but within a limited domain you might be able to do it. For instance, here's a naive version that would probably work for many data sets, including your example, though again it would not work with all data sets by any means:
<?php
$str = json_encode($array);
$str = preg_replace('/"([A-Za-z0-9_$]+)":/', '$1:', $str);
?>
var x = <?php echo json_encode($array); ?>;
That assumes anything that consists of just A-Z, a-z, 0-9, _, or $ between double quotes followed immediately by a colon is a key and removes the quotes. (That's not a complete list of valid JavaScript identifier characters, it's just an example.)
But it seems unlikely to me that the savings are worth the bother.
To do it correctly, of course, you'd have to do your own serializer. It wouldn't be all that hard, just a recursive function that handles descending into arrays and objects. It could still use json_encode for the values.

json_encode() gives special charactors like '\n'..how can i replace them in PHP?

I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));

Forward slash is changing to backward slash and forward slash

I have converted normal text into json with json_encode(data), but the problem is
normally written images/data.png is converted to images\/data.png i have to remove this extra backslash. How is it possible
In a JSON string, / and \/ are equivalent. You should not need to enforce the former syntax.
If you think you need to change them then you are either:
Designing too much for text editors instead of JSON parsers or
Being overly concerned with individual bytes
Escaping / provides a defence against premature script termination when you have code like this:
<?php
$data = Array( "</script>" );
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
That said, if you really want to remove it, PHP provides an option for it:
json_encode($data, JSON_UNESCAPED_SLASHES);

PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()

I'm currently making a web app for my workplace, that downloads around 40,000 rows of data from an SQL table in one go, places the data into nested PHP arrays, and then attempts to echo the JSON encoded array, where a JavaScript variable should capture the contents.
If I attempt to echo the data straight into the tags, it works fine - everything is displayed perfectly - formatted as a JSON encoded string. If, however, I attempt to echo the data into <script> tags, between speech marks '' or "", it throws an error in chrome, saying 'Uncaught SyntaxError: Unexpected identifier' - and when I attempt to scroll to the end of the (very long) string, it appears to have been chopped off, only a few thousand characters in.
The string is actually 1,476,075 characters long.
How do I get around this? I'm remaking the application - it originally basically combined javascript with the SQL results whilst iterating through the results rows, but this was so slow and clunky, so I figured an easier and quicker way to move the data from PHP to JavaScript, would be with a large JSON encoded string.
Any advice would be greatly appreciated.
Dan.
json_encode() takes care of ALL the quoting/escaping that needs to be done:
<?php
$foo = 'this is a simple string';
?>
<script>
var foo = "<?php echo json_encode($foo); ?>"; // incorrect
var bar = <?php echo json_encode($foo); ?>; // correct
The above construct would create:
var foo = ""this is a simple string"";
^--- your quote
^---the quote json_encode added
var bar = "this is a simple string"; // all-ok here.

Categories

Resources