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);?>;
Related
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
I have a products table that has foreign characters. Now I am trying to use the php array in javascript to narrow a dropdown box as the user types. Everything works except when there is a foreign character (like a carrot or tilde above a letter). How can I encode the the php array into the javascript array with these characters?
$jpro=json_encode($pro, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE);
var phpPro=<?php echo $jpro; ?>;
The errors Im getting are
var phpPro=;
"Uncaught SyntaxError: Unexpected token ;"
With JSON_HEX_APOS|JSON_HEX_QUOT you're telling json_encode to convert apostrophes and quotes to \u0027 and \u0022 respectively, but then negate it with JSON_UNESCAPED_UNICODE. And the reason you're getting that error is because you haven't put the PHP code in the variable inside quotes.
Now, since json_encode returns an array with quotes, e.g. [ "Österreich", "Gemüse" ], you can't just place the code inside them, but need to use apostrophes.
Ultimately, the following would be correct*:
$jpro = json_encode($pro, JSON_UNESCAPED_UNICODE);
var phpPro = '<?php echo $jpro; ?>';
Granted, this is going to return a string, not an array if that was your intention. If you want to transform it back to an array, just use JSON.parse:
var phpPro = JSON.parse('<?php echo $jpro; ?>');
* correct in the sense that it does what you're asking, but you really should never mix JavaScript and PHP together — especially not if you're dealing with user input.
This question already has an answer here:
Parse escaped JSON in PHP
(1 answer)
Closed 6 years ago.
How can I parse a string, like the following that I got from the API response:
"{\"response\":\"data\"}"
I need the "data" from the "response".
How can do that in PHP or in JS?
The response is a JSON string with quotations escaped. In JS, you can parse it using JSON.parse(myJsonString);
console.log(JSON.parse("{\"response\":\"data\"}").response);
Your question is a possible duplicate of Parse escaped JSON in PHP
First we need to remove the escape char \ using stripslashes:
$input = "{\"response\":\"data\"}";
$input = stripslashes($input);
Then you can insert the content into an array using json_decode with second parameter true (so you get an array instead of an object):
$input = json_decode($input,true);
So in a single line:
$input = json_decode(stripslashes($input),true);
You can access data and response as:
$input['data']; $input['response']
It is not clear if you need to do this in js or php. The above is the php solution.
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));
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.
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);?>;?