Parsing JavaScript (Not JSON) in PHP

Parsing Javascript (not JSON) in PHP

Pear Services_JSON will parse that string (tested version 1.31). But given that that is a JSON parser and that this isn't valid JSON you have no guarantee that future versions will still work.

javascript parse.json error with data from php json_encode

You seem to be doing two things:

  1. Generate JSON.
  2. Insert such JSON inside a JavaScript string literal.

Remember that JSON is not JavaScript. JSON is just a plain text data format while JavaScript is a full-fledged programming language. They're often confused because the former was inspired in the syntax of certain data structures from the latter, but that's where the similarity ends.

Dealing with #1 is easy: PHP has a function specifically designed for it, json_encode(), and in my experience it's rock solid.

Dealing with #2 is not as straightforward, though. PHP has functions (better or worse) to escape literal data in HTML, URLs or SQL, but it's never really had a specific function to do that same job in JavaScript strings.

Shall we write our own function? Luckily not. Here's where the similarity between JSON and JavaScript comes to help us. It happens that we can also use json_encode() to escape raw input in JavaScript strings because JSON syntax is a subset of JavaScript string syntax. But... JSON has to be an object or an array, doesn't it? That's true. Luckily, PHP comes to the rescue because:

PHP implements a superset of JSON as specified in the original RFC 7159.

[...]

Like the reference JSON encoder, json_encode() will generate JSON that is a simple value (that is, neither an object nor an array) if given a string, integer, float or boolean as an input value. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.

Source

In other words, json_encode() also produces JSON fragments. So you can do this:

<?php
$result = 'val01\test\val04'; //these are the data that are get from DB
$example = ['testData' => $result];
$json = json_encode($example);
$javascript = json_encode($json);
?>
<script>
var json = <?php echo $javascript; ?>;
var obj = JSON.parse(json);
</script>

Which renders:

<script>
var json = "{\"testData\":\"val01\\\\test\\\\val04\"}"
var obj = JSON.parse(json);
</script>

And works as expected once in the browser:

var json = "{\"testData\":\"val01\\\\test\\\\val04\"}"var obj = JSON.parse(json);console.log(obj.testData);

Cannot parse JSON returned from PHP

You have to populate array correctly before converting to JSON with PHP

$data = array();
$data = [];
array_push($data,
array( "Date" => "11/11/2015",
"Number" => "123",
"Status" => "Order Received"
));

echo json_encode($data);

This will give you following output:

[{"Date":"11\/11\/2015","Number":"123","Status":"Order Received"}]

Do I need json.parse if I've used json_encode()?

Yes it is valid, because JSON syntax is a subset of JavaScript object literal syntax. Therefore if you inject JSON-encoded text into generated JS code in the way you've shown then it behaves as an object literal, just as if you'd written it there by hand.

JSON.parse would be required if you were receiving a string containing JSON-encoded text into a JavaScript variable (e.g. as the result of an AJAX request) and needed to convert it from a string into a usable object.

Why don't I have to decode/parse a JSON string generated by PHP in JS

When you do this:

<script>
var phpVars = <?php echo json_encode($vars); ?>;
</script>

you're generating JavaScript code with PHP. So what actually goes to your browser is:

<script>
var phpVars = /*...THE_JSON_GOES_HERE...*/;
</script>

Note that it's not in quotes or anything. Your example code will produce a JSON string that looks something like {"fetchPath":"/path/to/my-url.php"}, so what the browser would see is:

<script>
var phpVars = {"fetchPath":"http:\/\/my.website.com\my-url.php"};
</script>

Since JSON is a subset of JavaScript object initializer syntax, that's perfectly valid JavaScript code. The parser parsing the script tag contents parses it as code, not as JSON. But that's fine, because as long as it's used as a right-hand value (e.g., on the right-hand side of = or passed into a function, etc.), JSON is valid JavaScript.

PHP JSON header causes error on JSON.parse (using jQuery)

If you don't specify a dataType then jQuery will determine what type of data is received from a URL using the Content-Type header and run it through an appropriate parser.

json is not a string of JSON, it is a JavaScript object that you got from parsing the JSON.

The input to JSON.parse needs to be a string of JSON.

Change:

function (json) {
var response = JSON.parse(json);

To:

function (response) {


Related Topics



Leave a reply



Submit