JSON parse and single quote - javascript

I have JSON data passed by PHP and I need to parse it in Javascript.
item = JSON.parse('<?=json_encode($item_localized);?>');
Some trouble. I have string in $item_localized which contains single quote. Jsonlint says it valid json. Because I use '<?=json_encode($item_localized);?>' - I receive message Uncaught SyntaxError: Unexpected identifier. I cannot use double quotes. I tried replace single quotes with \' but it's not working.

json_encode will generate a JSON text.
JSON.parse needs to receive a string containing a JSON text.
You do need to quote the string, but you can't simply place ' around it because that won't escape any characters in the string that have special meaning in a string literal (like other ' characters).
If you put a string into json_encode then you will get out a JSON text consisting of a string representation of another JSON text. Since JSON is a JS subjet, that string will be JS safe:
item = JSON.parse(<?php echo json_encode(json_encode($item_localized)); ?>);
This is, however, silly. Since JSON is a subset of JavaScript, you can just use it directly as a JavaScript literal.
item = <?php echo json_encode($item_localized); ?>;

What about item = <?=json_encode($item_localized);?>;?

Related

JSON.parse ends up in 'missing ) after argument list'

I want to pass an php array to js. For this purpose I use json_encode an then in js JSON.parse().
Now the Problem ist, that JSON.parse trow an exception 'missing ) after argument list'. I guess it's apostrophes in numbers (number_format > CHF).
clippings:
<script>
(function($) {
var prices = JSON.parse('<?= $this->prices_json; ?>'); ...
... "offsetdruck_4f":{"1s":"583.82","2s":"1'090.09"}...
have single quotes to be escaped? If so, how best to do it?
is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
have single quotes to be escaped?
Single quotes inside a JavaScript string literal that is delimited with single quotes do have to be escaped.
… and that is what you have: 'data with ' and then at the end'.
If so, how best to do it?
To not use a JavaScript string literal at all.
JSON is a subset of JavaScript literal notation, so just treat it as JavaScript. Don't try wrapping it in a string and then explicitly parsing it.
var prices = <?= $this->prices_json; ?>;
try php: addslashes(json_encode($php array))
have single quotes to be escaped? If so, how best to do it?
json_encode should escape everything needs to be escaped.
is json_encode an then in js JSON.parse the best practice to pass an php-Array to js (at a template)? If not, how best to do it?
You should use json_encode in order to be sure that the output is correct. Do not rely on default array output. It has nothing to do with JSON.
You don't need to use JSON.parse here at all.
var prices = <?= json_encode($this->prices_json); ?>;

SyntaxError: Unexpected token \ in JSON at position

I'm trying to parse a String to JSON in NodeJS/Javascript, this is my string (which I cannot change, coming from an external database):
'{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}'
I'm calling:
JSON.parse(row.raw_data)
But are getting:
SyntaxError: Unexpected token \ in JSON at position
I actually thought double escape was the correct way of escaping in string/JSON.
Your JSON is invalid. You've said you can't change it, which is unfortunate.
It looks like it's been double-stringified but then the outermost quotes have been left off. If so, you can fix it by adding " at each end and then double-parsing it, like this:
var str = '{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}';
str = '"' + str + '"';
var obj = JSON.parse(JSON.parse(str));
console.log(obj);
Ideally, though, you'll want to go through the database and correct the invalid data.
I actually thought double escape was the correct way of escaping in string/JSON.
In JSON, strings are wrapped in double quotes ("), not double escapes. You only escape double quotes within strings (with a single \).
If you've been creating JSON strings manually (in code), don't. :-) Instead, create the structure you want to save, and then stringify it. Building JSON strings manually is error-prone, but a proper JSON stringifier will be reliable.

Getting rid of ' " ' from json_encode [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have a code snippet that is encoding a PHP array into json but when i am trying to parse it it gives me error because of " present in value
PHP array
$arr = array( id => 1, msg => <h1>Some text</h1> <img src="http://test.png">);
Js code
var json = JSON.parse('<?php echo json_encode($arr);?>');
When i json_encode the above error it surrounds string with double quotes that breaks my JSON.parse function. I tried using replace function but after json_encode it automatically adds double quotes surrounding the string values of object.
So i tried to replace all " with ' but it is replacing all double quotes. i am thinking can it be done by regex to replace only " in html elements or something else. I could not escape HTMl at time of saving because a large number of data is already present in the database and changing it is bit difficult.
JSON is already parsed the moment PHP does print it.
var json = <?php echo json_encode($arr); ?>;
When do you need JSON.parse() then?
JSON.parse() turns an already escaped JSON into a JSON/Javascript object.
JSON.stringify() does the exact opposite, escaping JSON to a string.
When inserting JSON into JavaScript, it is not necessary to wrap it in quotes or even try to parse it, because JSON is a valid JavaScript object or array literal. By removing the quotes, you eliminate the problem of needing to escape quotes.
var json = <?php echo json_encode($arr);?>;

Why am I getting an error message about "unexpected non-whitespace after JSON data"

Can anybody tell me what the problem is with this:
I am echoing out a PHP array into javascript as follows:
<?php
$myArray=array();
foreach ($persons as $person) {
array_push($myArray,$person['id']);
}
?>
$(document).ready(function() {
populatePersons(JSON.parse(<?php echo json_encode($myArray);?>));
});
So basically I am echo'ing out a PHP array in json format, and then parsing it in javascript but I am getting this error in my console log:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Can anybody tell me what I am doing wrong?
Can anybody tell me what I am doing wrong?
While json_encode produces JSON, you are echoing it into JavaScript. As such it will be interpreted as a JavaScript array literal, not a string containing JSON. Hence you cannot use JSON.parse.
Just get rid of it:
populatePersons(<?php echo json_encode($myArray);?>);
If you looked at the generated code, you would something like:
populatePersons(JSON.parse([1,2,3]));
But JSON.parse expects a string (containing JSON). Because JavaScript performs type conversion, it will convert the array to a string first, which likely does not result in valid JSON.
Again: You already have an array, there is no need to parse anything.
Its because youre feeding JSON.parse an array. Just get rid of the JSON.prase in your javascript and replace it with JSON.stringify if youre trying to display the json. If not, then json_encode($myArray) should be enough for operations.
<div id = 'test'></div>
<script>
var test = document.getElementById('test');
test.innerHTML = JSON.stringify(<?php echo json_encode($myArray)?>);
</script>
Try putting the json_encode string in quotes.
populatePersons(JSON.parse('<?php echo json_encode($myArray);?>'));
As the parameter expected is string.

correctly adding to json from javascript

hi im having trouble correctly adding to my json
here is the code.
When i console.log the string im trying to add is
{"type":"#","name":"wh2xogvi","list":[{"0":"background-color"},{"1":"border"},{"2":"width"}, {"3":"height"},{"4":"margin"}],"listvalues":[{"0":"#aaa"},{"1":"2px solid #000"},{"2":"1040px"},{"3":"50px"},{"4":"0 auto"}]}
it is valid json
var jsonltoload = JSON.stringify(eval("(" + jsonloadtostring + ")"));
console.log(jsonltoload); // this is the console log i was talking about higher up
fullJSON.styles.objectcss.push(jsonltoload);
But when i actually look at the json it is wrong ends up something like this
"{\"type\":\"#\",\"name\":\"unkd42t9\",\"list\":[{\"0\":\"background-color\"},{\"1\":\"border\"},{\"2\":\"width\"},{\"3\":\"height\"},{\"4\":\"clear\"}],\"listvalues\":[{\"0\":\"#ddd\"},{\"1\":\"2px solid #000\"},{\"2\":\"100%\"},{\"3\":\"50px\"},{\"4\":\"both\"}]}",
the fullJSON comes from JSON.parse(json); which comes from a file
You seem to confuse JSON, a textual, language-independent data representation, with JavaScript objects, a language-specific data type.
JSON.stringify returns a string (containing JSON), so jsonltoload is a string. I guess you simply want to parse the JSON and add the resulting object:
var obj = JSON.parse(jsonloadtostring);
fullJSON.styles.objectcss.push(obj);
I think the JSON string is trying to escape the double quotes character you have added to string, resulting in the string. try to enclose the whole string with single quotes rather than double quotes

Categories

Resources