PHP JSON Parser v.s. Javascript JSON Parser - php

I have an array via json_encode of PHP serialize:
json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
// output json: {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
I tried to decode in Javascript:
JSON.parse('{"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}');
Then I don't understand why do I get an error "Uncaught SyntaxError: Unexpected token w" ??
Is PHP and Javascript JSON parser difference?

The problem is because you're using JSON.parse() and enclosing your JSON string in single quotes.
So your escaped regex string gets unescaped in the interpretation of the outer string-literal (single-quoted), and then gets mixed up in the interpretation of the value of the string pattern (double-quoted), ultimately causing JavaScript to choke trying to decipher "\w".
The following example, mimicking PHP rendering the JSON verbatim to a declaration, works fine in a JS console:
var json = {"pattern":"^(?:\/?site\/(?[\\w\\-]+))?(?:\/?intl\/(?[a-z]{2}(?:\\-[a-z]{2})?)\/?)?(\/?(?.*))"}
If you want to use JSON.parse, you have to first double-escape your JSON string in PHP
$json = json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))'));
$json = str_replace('\', '\\', $json);
// output json: {"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}
Then, in JS:
var json = JSON.parse('{"pattern":"^(?:\\/?site\\/(?[\\\\w\\\\-]+))?(?:\\/?intl\\/(?[a-z]{2}(?:\\\\-[a-z]{2})?)\\/?)?(\\/?(?.*))"}')

Related

Storing JSON as a string in JSON using PHP

For testing purposes, I wish to use Ajax to request some JSON from the server. From the Ajax client's perspective, the JSON should look like:
json=[
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'},
{"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'}
];
Note that jsonstring is not JSON, but a string, and $.getJSON() should not parse it into an object.
My attempt is below, however, I get error Parse error: syntax error, unexpected ',' in /var/www/test/src/classes/Ajax.php on line 13.
How should this be performed?
$content=file_get_contents('../buffer.json',true); //Line 13
$buffer=$content?json_decode($content):[];
$json=json_encode(['a'=>1,'b'=>2,'c'=>3]);
$buffer[]=[
'source'=>'pa',
'jsonstring'=>'"'.$json.'"'
];
$buffer=json_encode($buffer);
file_put_contents('../buffer.json',$buffer);
header('Content-Type: application/json');
echo($buffer);
buffer.json output is shown below:
[{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""},{"source":"pa","jsonstring":"\"{\"a\":1,\"b\":2,\"c\":3}\""}]
Have you tried removing the extra quotes from 'jsonstring'=>'"'.$json.'"'? If you json_encode it (which it looks like you do), then it is already a string. I think it should be 'jsonstring' => $json.

JSON - proper way to decode string in JavaScript

I'm wondering what would be the best way to decode JSON string inside Javascript code.
I want my json string to be embeded inside my JS, like this:
var params = dojo.fromJson('<?=json_encode($this->params); ?>');
dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side.
It seems that json encoder ignores ' chars and only converts " to \". So when one of my variables inside $this->params contains a ' character there is a Javascript error.
For example:
var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');
What is the best way to approach this ?
Thanks for help.
Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead.
var params = <?=json_encode($this->params); ?>;
PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data.

json_decode failing

I have the following JSON formatted string:
{
"hooks":[
{
"type":"subscribe",
"id":1331741592.6925,
"email":"JoeX#test-email.com",
"status":"Active",
"custom_fields":"{\"first_name\":\"Joe\",\"last_name\":\"X\"}",
"ip_created":"24.199.200.142",
"list_id":"33",
"list_type":"internal",
"list_name":"Administrator List 2",
"list_optin":false
},
{
"type":"subscribe",
"id":1331741592.7067,
"email":"JaneY#test-email.com",
"status":"Active",
"custom_fields":"{\"first_name\": \"Jane\",\"last_name\":\"Y\"}",
"ip_created":"24.199.200.142",
"list_id":"33",
"list_type":"internal",
"list_name":"Administrator List 2",
"list_optin":false
}
]
}
I want to use the PHP json_decode() function to put it in an associative array.
When I do run the script, debugging shows the value of the new array as null, so I presume the decode is failing. We aren't running PHP 5.3, so I can't use json_last_error(). Here is the code:
$hooks = (the JSON string from above);
$hooksArray = json_decode($hooks, true);
Any ideas why the $hooksArray is coming back null?
Is the JSON string inside your PHP source? Perhaps it's not interpreting the escaped backslashes correctly.
I tried the following experiment in Python for reference: Dumped the JSON data into a multi-line string via the REPL and decode it with json.loads(). It choked on the in-string quotes in the first instance of the custom_fields string. When I examined the multi-line string, all the escapes were gone, leaving me only with the quotes.
When I put the same JSON data in an external file and loaded it, it worked fine.
I put the JSON data in an external file and replaced all '\"' instances with '\\"' and then the first experiment started to work.
Maybe that will work for you too.

php addslashes becomes illegal token in javascript

i tried using jquery ajax call, everything works fine until i tried to escape the json string using addslashes on the the server side i get the follow error : unexpected token illegal. here is my json string i cant find any problems in it
[{\"shortlist\":{\"id\":\"46\",\"application_id\":\"3\",\"created\":\"2012-04-
22\",\"modified\":\"2012-04-22\"},\"application\":
{\"id\":\"3\",\"admissionsession_id\":\"0\",\"school_id\":\"\",\"surname\":\"oni\",\"
other_names\":\"oluwafemi timothy Toluwalope\",\"date_of_birth\":\"0000-00-
00\",\"created\":\"2012-04-15\",\"modified\":\"2012-04-15\"}}]
if i remove the addslahes from the php json string it works fine. am scared of leaving my string unescaped tho.
add your data structure in an array:
$data = array('shortlist' => array('id' => 46, ....
then use:
$json = json_encode($data);
echo $json;

JSON Encode/decode doesn't work as it should

I am preparing and sending a JSON string from my PHP file to my Javascript function like this:
$json = array();
$json['slice'] = false;
$json['G500'] = false;
$json['KG1'] = false;
$encoded = json_encode($json);
die($encoded);
However, in my JS function, if I do this, it is unable to decode the JSON object:
var d = req.responseText;
var jsonObject = eval(d);
The only way, I can get it to eval the JSON object is by adding parentheses manually
jsonObject = eval("(" + d + ")");
I have the same problem going in reverse as well. Sending a JSON object to PHP and trying to decode it there fails. I believe I would need to remove the parentheses in my PHP script before attempting to decode.
Why is this happening? Is there something I can do to work around this incompatibility?
EDIT:
PHP to JS is now working if I use JSON.parse. I'm still having trouble the other way around.
This is how I'm sending the data to the PHP:
var JSONstring =
{
"Product": document.getElementById('item').value,
"Size": document.getElementById('size').value,
"Quantity": document.getElementById('quantity').value
};
url = "maintainOrder.php?json=" + JSON.stringify(JSONstring);
req.open("GET", url, true);
However, the PHP script is unable to decode it.
$newItem = json_decode($_GET['json']);
array_push($_SESSION['order'],$newItem);
Your Javascript
eval has an issue with leading { characters, because of an ambiguity with block scope.
Using the parentheses to force the input to be parsed as an expression is a solution, but you should avoid eval entirely and use a proper JSON decoding function.
Your PHP
We'd need to see the data that you send to your PHP script to know why it won't parse. In general, as long as JSONLint accepts your JSON, so will PHP's json_decode. So give that a go.
For the php to javascript issue refer to the Tomalak Geret'kal answer.
For the javascript to php maybe I have the solution:
If you want an associative array in php then you have to pass assoc parameter as true into json_decode (default to false)
Example:
$array = json_decode($jsonString, true);
I was bitten a couple of times by this: by default json_decode try to create an object if it receive a javascript object (it make perfect sense if you think of) and you have to force it to render an associative array if you need this behaviour
I think you need to do some string processing, all you need to do is echo and see the exact format of your JSON string and make sure it conforms to the standard format, then use string processing both on the server and client sides to achieve the desired effect
Are you sure php is not adding slashes to the json text?, try saving the json text in a file in the server side to verify

Categories