How to use a JSON literal string? How to use a JSON literal string? javascript javascript

How to use a JSON literal string?


In JavaScript - the string '{"prop":"val\'ue"}' is a correct way to encode the JSON as a string literal.

As the JavaScript interpreter reads the single-quoted string, it will convert the \' to '. The value of the string is {"prop":"val'ue"} which is valid JSON.

In order to create the invalid JSON string, you would have to write '{"prop":"val\\\'ue"}'

If I understand the question right, you are trying to generate JavaScript code that will set some variable to the decoded version of a JSON string you have stored in the database. So now you are encoding the string again, as the way to get this string into JavaScript is to use a string literal, passing it through JSON.parse(). You can probably rely on using the server side JSON encoder to encode the JSON string as a JavaScript string literal. For instance:

<?php $jsonString = '{"prop":"val\'ue"}'; ?>var myJson = JSON.parse(<?php echo json_encode($jsonString) ?>);// Prints out: // var myJson = JSON.parse("{\"prop\":\"val'ue\"}");// And results: Object - { prop: "val'ue"}

However, If you are 100% sure the JSON is going to be valid, and don't need the weight of the extra parsing / error checking - you could skip all that extra encoding and just write:

var myJson = <?php echo $jsonString; ?>

Remember, JSON is valid JavaScript syntax for defining objects after all!


According to jsonlint it is valid without escaping the single quote, so this is fine:

{"prop": "val'ue"}

But this is invalid:

{"prop":"val\'ue"}

According to json.org json:

is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others

So it is the language conventions in c-type languages regarding the reverse solidus (\) that means that your example is not valid.


You might try the following, however, it's ugly.

JSON.parse("{\"obj\":\"val'ue\"}");

Or just store the string to a var first. This should not store the literal backslash value and therefore the JSON parser should work.

var str =  '{"obj" : "val\'ue"}';JSON.parse(str);