Home » Jquery » php – JSON.parse generates error with backslash

php – JSON.parse generates error with backslash

Posted by: admin February 22, 2020 Leave a comment

Questions:

Why does the following JSON fail to be parsed by JSON.parse?

{"page_title":"contact us","val":{"pattern":"/email/\s+us\s*(.*?)/\s/","type":"1"}}

When I log result to the console then it gives above output. After using JSON.parse it gives this error :

Uncaught SyntaxError: Unexpected token s in JSON at position 1649 at JSON.parse ()
see my code below:

var result ='<?php echo json_encode($output);?>';
console.log(result);
var data = JSON.parse(result);
How to&Answer:

Use addslashes function because you are using regex into string

var result ='<?php echo addslashes(json_encode($output));?>';

Answer:

Simple… don’t single-quote wrap your json object nor call JSON.parse().

let result = <?php echo json_encode($output); ?>;

Now result is a javascript object that is ready to use.

If you are json_encode() properly, your string will look like this:

Code: (Demo)

$array = [
    "page_title" => "contact us",
    "val" => [
        "pattern" => "/email/\s+us\s*(.*?)/\s/",
        "type" => "1"
    ]
];

echo json_encode($array);

Output:

{"page_title":"contact us","val":{"pattern":"\/email\/\s+us\s*(.*?)\/\s\/","type":"1"}}

p.s. your regex pattern looks questionable with those unescaped slash after email and after the capture group despite the pattern having slashes as delimiters.

If this pattern is for js execution, you might have better success with:

email\/\s+us\s*(.*?)\/\s

without delimters so that your pattern can be used by a regex function as a variable.

And if my above logic doesn’t scream loud enough, here is a javascript demo that shows that json_encode() does not need addslashes():

The below data variable will be populated by:

data = <?php echo json_encode([
                      "page_title" => "contact us",
                      "val" => [
                      "pattern" => "email\/\s+us\s*(.*?)\/\s",
                      "type" => "1"
                  ]
                  ]); ?>;
let data = {"page_title":"contact us","val":{"pattern":"email\\/\s+us\s*(.*?)\\/\s","type":"1"}},
    str = "You can email/ us all-day-long if you wish/  or not.";

console.log(data.page_title);
console.log(data.val.pattern);
regex = new RegExp(data.val.pattern,"g");
console.log(str.match(regex));
console.log(data.val.type);