Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript:: JSON parse does not accept line breaks?

I wrote a sample code just to explain what I was after so...

Here is a working example:

var json='{"hezi":"firstName","gangina":"lastName"}',
    obj=JSON.parse(json);

alert(obj.gangina);

And here is the same exact code with line breaks and tabs (just to make the code more readable since in my real code the JSON array string is HUGE):

var json=
'
    {
        "hezi":"firstName",
        "gangina":"lastName"
    }
',
    obj=JSON.parse(json);

alert(obj.gangina);

I even tried to compensate with :

    obj=JSON.parse(json.replace(/(\r\n|\n|\r|\t)/gm,""));

So... Technically I can solve this issue by compressing my line (removing all \r\n|\n|\r|\t manually) but I'm quite sure there is a quick fix for that regardless beautifying my code.

Small tweak needed here...

like image 209
Hezi-Gangina Avatar asked Dec 05 '22 03:12

Hezi-Gangina


2 Answers

JavaScript does not accept line breaks without escaping. You can fix this by escaping the line breaks:

var json=
'\
    {\
        "hezi":"firstName",\
        "gangina":"lastName"\
    }\
',
obj=JSON.parse(json);

alert(obj.gangina);
like image 106
jehna1 Avatar answered Dec 09 '22 14:12

jehna1


I suppose you want to 'pretty print' long JSON-strings?

In that case: you can use the space parameter in JSON.stringify to display a long JSON-string formatted. See MDN. For example:

var json = '{"hezi":"firstName","gangina":"lastName"}'
    obj = JSON.parse(json);

document.querySelector('#result').innerHTML = JSON.stringify(obj, null, ' ');
<pre id="result"></pre>
like image 20
KooiInc Avatar answered Dec 09 '22 15:12

KooiInc