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.
Related
i need to remove () backslash in my string when using echo json_encode()?
my example..
$song_url = 116e9155e0afc11555cf33dc9c9bd25d.mp3
$resmsg[] = array("Song_name"=>"$song_name","Song_URL"=>"http://www.kbmusique.com/songs/$song_url");
echo json_encode($resmsg);
my output is
[{"Song_name":"djigh araouioui","Song_URL":"http:\/\/www.kbmusique.com\/songs\/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
but i need as
[{"Song_name":"djigh araouioui","Song_URL":"http://www.kbmusique.com/songs/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
Is there a way to solve this? Thank you.
Your comment indicates that you just need to get a copy/pastable URL for testing.
Just parse the JSON and extract the piece of data you need from it. i.e. If you want a text representation of something, then convert the JSON to text, don't try to hack the JSON into a specific form.
You could do this in PHP with json_decode, in a browser with JSON.parse(), or just use a tool such as the Chrome JSONView extension.
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})?)\\/?)?(\\/?(?.*))"}')
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
I need someone to shed some light on this subject.
When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.
The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Edit: Is it because it treats the data recieved from the php file as text and not as javascript?
Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?
Thank you in advance.
JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)
To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:
var json = '{"thing":1, "thang":"two"}';
var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere
Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:
jQuery.get('http://domain.com/path/to/request', function(obj)
{
// string is automatically converted to an object,
// usable as array or with dot notation
alert(obj.thing);
alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html
You can always use a library like jQuery, Mootools, Prototype, etc. for the decoding JSON text to Javascript variables..
JSON is something like serialize from PHP :) It's a way to transform string to object and back :)
Here's my problem. I have data being returned using JSON, AJAX from my php script to my page. The data is being stored in a variable data
Using the variable data, I'm trying to construct a div using javascript. However, if the data contains a single quote, it break my js code and the page script doesn't work.
example code with data being the variable containing data "The boy's bicycle":
var newrootcomment = $("<div id='container'>" + data + "</div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
How do I solve this problem?
Are you using the json_encode function available in PHP? Are are you treating the response as JSON? jQuery.parseJSON(<json-string>).
From there you interact with it simple as an object.
var resp = {};
If you don't have jQuery, most browsers support JSON.parseJSON().
Also, make sure you use double quotes for attributes.
<div id="foo"></div>
This is normally how I use json_encode:
$resp = array(
"foo"=>"foo_value",
"bar"=>"bar_value",
"foo_bar"=>array("one","two",3),
"message"=>"AWesome"
)
return json_encode($resp)
Take a look at json_encode for PHP - it'll return a quoted string with JSON-safe characters - it'll escape entities like \n, \, ". etc
Edit
Note that a single quote in JSON is not required to be escaped since it surrounded by double quotes.
From what you said in a comment to #jbcurtin's answer, about your PHP code being echo json_encode('{ "author": "'.$author.'"}'); I'd say that that is one problem. You don't need to encode the entire string, only the author variable. That line should be echo '{"author": '. json_encode($author) . '}'; instead.