Convert php array to javascript utf-8 array [duplicate] - javascript

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.

Related

Parse strange json string in php into js [duplicate]

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.

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);?>;

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.

Javascript eval fails on complicated json array [duplicate]

This question already has answers here:
JSON Javascript escape
(4 answers)
Closed 7 years ago.
I want to convert a json string to object by eval, but it fails with error like:
Uncaught SyntaxError: Unexpected identifier VM250:1
below is my string:
'[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
Seems there is something wrong in the bold part, but i don't know how to fix it
The code below is not working
var m='[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}]';
eval(m);
The code below is working so i think the data structure of this json string is ok
var m=[{"quiz_id":"3","_id":"1","option_in_json":"[{\"option\":\"1\",\"is_answer\":false},{\"option\":\"2\",\"is_answer\":true}]","question":"1+1"}];
alert(m[0].option_in_json);
Also tried with $.parseJSON with no luck
It does not work because you are not escaping the data inside the string literal correctly. Look at the value of m in the first case, especially the quotation marks:
[{"option_in_json":"[{"option":"1","is_answer":false}]","question":"1+1"}]
// ^ ^
I removed some irrelevant data. You should be able to see that this cannot be valid JavaScript (or JSON), because the quotation mark before option terminates the string.
In order to put the data inside a string literal, you should either fix the data so that it doesn't contain nested JSON, or escape \:
'[{"option_in_json":"[{\\"option\\": ... }]"}]'
Better of course if you are not putting it in a string literal in the first place.
var m='[{"quiz_id":"3","_id":"1","option_in_json": [{"option":"1","is_answer":false},{"option":"2","is_answer":true}],"question":"1+1"}]';
// ^-- don't wrap in "" so no need to escape inner double quotes.
console.dir(JSON.parse(m));

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