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.
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.
In mysql database, "diagID" is saved as json_encoded(array). Now i need it to retrieve in ajax success.
How to convert JSON parse data into array, as it's showing string?
var ajaxResponse= {
"id": "123",
"diagID" : "['101','125','150','230']"
}
typeof(ajaxResponse.diagID)
= string
In javascript typeof(ajaxResponse.diagID) shows string. How to convert it into array?
Decoding it in php would make most sense
$diagID = json_decode($diagID, true);
Then when you json_encode() the whole response it won't have the extra wrapping quotes.
Note however that the strings in array have single quotes which are not valid json and need to be replaced with double quotes before they can be parsed in either language
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);?>;
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));
This question already has answers here:
Serializing to JSON in jQuery [duplicate]
(11 answers)
Closed 9 years ago.
How to insert text into json array using jquery/javascript .
supposing I have data as
some numbercodes in a text file format 123, 456, 789
I want to get them in a json array format using javascript/jquery.
var nuumbercodes = [ "123","456","789" ];
If you have a well formatted text string with comma separated numbers, like this '123,456,789'
This should have no spaces or tabs,
Then you can convert it simply into a JavaScript array.
var myTextwithNuumbercodes='123,456,789';
var numbercodes=myTextwithNuumbercodes.split(',');
returns ['123','456','789']
if you have a JSON string like this '[123,456,789]' then you get a javascript array by calling JSON.parse(theJSONString)
var numbercodes=JSON.parse('[123,456,789]');
returns [123,456,789]
notice the "[]" in the string ... that is how you pass a JSON array
toconvert it back to a string you can use JSON.stringify(numbercodes);
if you have a total messed up text then it's hard to convert it into a javascript array
but you can try with something like that
var numbercodes='123, 456, 789'.replace(/\s+/g,'').split(',');
this firstly removes the spaces between the numbers and commas and then splits it into a javascript array
in the first and last case you get a array of strings
u can transform this strings into numbers by simply adding a + infront of them if you call them like
mynumbercode0=(+numbercodes[0]);// () not needed here ...
in the 2nd case you get numbers
if you want to convert an array to a string you can also use join();
[123,456,789].join(', ');
Assuming your data is in a string, then split it on commas, use parseInt in a for loop to convert the string numbers into actual Numbers and remove the whitespace, then JSON.stringify to convert to JSON.
You could use .push() push values at the end of an array. After that you could use JSON.stringify(nuumbercodes) to make a JSON string representation of your Array.