Hezi-Gangina
Hezi-Gangina

Reputation: 659

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...

Upvotes: 5

Views: 3846

Answers (5)

Lewis
Lewis

Reputation: 14906

ES6 template strings are now supported in Chrome 41+ and Firefox 34+. It's time to know about it.

JSON.parse(`
   {
        "hezi":"firstName",
        "gangina":"lastName"
    }
`);

Upvotes: 2

Dave Jones
Dave Jones

Reputation: 344

You need to use line breaks to achieve this but escaping is not recommended due to it being easy to escape a space by mistake which would throw a formatting error.

Use..

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

alert(obj.gangina);

But my question would be why use json in the 1st place, if hand coding use an object then this wouldn't be an issue, json data should only be loaded from external source.

Upvotes: 3

KooiInc
KooiInc

Reputation: 122936

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>

Upvotes: 3

Touffy
Touffy

Reputation: 6561

Just to clear up the confusion. The error is here:

var json=
'
    {

On line 2, there's a quote: the beginning of a string. Then an unescaped line break. That causes a SyntaxError and none of your code is ever executed. In particular, JSON.parse isn't executed.

Upvotes: 2

jehna1
jehna1

Reputation: 3130

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);

Upvotes: 7

Related Questions