It's worth noting that some browsers now provide a set of native functions for JSON decoding and encoding: JSON.parse() and JSON.stringify(). They are safer than using the eval() function and only works if the JSON data is well-formed, whereas eval() would evaluate things like the following:
{
'hello': (undefined
? 'world'
: ('number ' + Math.floor (40.235)))
}
What's wrong with that? The JavaScript value `undefined' is not available in JSON (only true, false, null, strings and numbers are allowed); single quotes are used everywhere when only double quotes are valid in JSON; you can't call JavaScript functions or perform string concatenation in JSON.
Obviously the last one is a big problem because you could receive some malicious JSON, possibly a value from a form input, that attempts to tamper with things. So when possible, use JSON.parse() and JSON.stringify()...because eval() is dangerous.
Edit:
I misread the original post. If you have a JSON object in PHP and you want to use it in JavaScript, you would need to convert the JSON object to a string and pass it on to JavaScript. The only way to do that would be to make your JavaScript code actually ask for the newly created JSON string in the first place. PHP would return a string, JavaScript would use eval() or JSON.parse() on the string, and you'd have your object in JavaScript. I'm not sure if there is a non-AJAX way to do this without making your JavaScript files into PHP files, setting the Content-Type header, etc., but I know that AJAX would work in this situation.