Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript decode JSON string which contains an encoded string

I have the following PHP code:

    $foo = new stdClass();
    $foo->test='hello world';
    $bar = new stdClass();
    $bar->foo = json_encode($foo);
    $encoded_string = json_encode($bar);

The $encoded_string contains:

{"foo":"{\"test\":\"hello world\"}"}

I want to parse this string from javascript (using jQuery's $.parseJSON for example):

var data = $.parseJSON('{"foo":"{\"test\":\"hello world\"}"}');
console.log(data);

I would expect something like the following to be logged:

Object {foo: '{"test":"hello world"}'}

But I get an Unexpected token t error when running it (using chromium)

How can I parse this json string in Javascript? Here's a fiddle if anyone wants to try.

like image 237
periklis Avatar asked May 20 '26 15:05

periklis


1 Answers

The problem that you're running into is that the output of json_encode is not meant to be used directly as a string in JavaScript.

json_encode outputs a usable JavaScript object:

<?php
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode($bar);
?>
var a = <?php $encoded_string ?>;
console.log(a.foo); // produces '{"test":"hello world"}'

If you want to needlessly parse the JSON output from a string value, you simply need to double encode $encoded_string:

<?php
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode(json_encode($bar));
?>
var aStr = <?php $encoded_string ?>;
var a = JSON.parse(aStr);
console.log(a.foo); //same as before

Of course, you should avoid using server side languages to generate JavaScript code, instead set up the data as either a data-* attribute or as a JSON source that can be requested with AJAX.

When the data is requested from the server (or from the attribute) it will be as a properly escaped JavaScript string, which is where JSON.parse will be necessary to parse the object.

like image 72
zzzzBov Avatar answered May 22 '26 05:05

zzzzBov