Jovan Perovic
Jovan Perovic

Reputation: 20201

json_encode with double quotes passed into JSON.parse

I have seen that this question has been asked too many times over the years. Still can't refrain from asking if anything was improved during this time.

Currently, I have PHP code:

$jsonData = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);

and then JS (Angular to be specific) comes into play:

var decoded = angular.fromJson('<?php echo $jsonData ; ?>');

The flags above do a very good job of keeping some of the issues at bay. However, given the example:

$data = ["name" => "Name \"Nickname\" Surname"];

JSON fails to parse. If I wrap the data with addslashes(), it does work, but then:

$data = ["name" => "Name 'Nickname' Surname"];

This fails.

Since the structure $data is highly unpredictable, and usually is 4-5 levels deep, my solution was:

array_walk_recursive($data, function(&$item, $key){
    $item = str_replace('"', '\"', $item);
});

This works, however, I am looking for some more knowledgeable source. I've read some other SO questions where people escape not only double quotes but line feeds, carriage return and backslashes as well.

The last thing I need is to fall into edge case trap :)

Any hints for me?

Upvotes: 2

Views: 676

Answers (1)

Kevin B
Kevin B

Reputation: 95056

Since json can be used directly as an object literal in javascript, you could use it like this:

var decoded = <?php echo $jsonData ; ?>;

thus eliminating the need to do any further parsing to avoid issues with ' or \ characters within the text. the json_encode should already be taking care of " charaters.

Upvotes: 3

Related Questions