JSON.parse gives error but with eval correct

1

I have

var data = '[
    { cod: 2, tipo: 'MAÑANA' }, 
    { cod: 4, tipo: 'NOCHE' }, 
    { cod: 3, tipo: 'TIENDAS V.O.' }
]';

When doing the json pass I get an error:

var aData = JSON.parse(data);

With eval goes well.

var data = eval(data);

What is the problem with parse?

    
asked by Joseba Rodríguez 12.02.2018 в 10:55
source

1 answer

3

You are confusing the syntax of a Javascript object with JSON: JSON is a stricter notation:

  • You can not use single quotes as delimiters.
  • It is mandatory to put the names of the attributes (the keys) in quotes.
  • Therefore a valid JSON would be:

    var data='[{ "cod": 2, "tipo": "MAÑANA" }, { "cod": 4, "tipo": "NOCHE" }, { "cod": 3, "tipo": "TIENDAS V.O." }]';
    
    var parsedData=JSON.parse(data);
    
    console.log(parsedData)

    By the way, I advise you to use the single quotes to delimit text in Javascript, that way you can use the doubles internally without having to escape them "\"así\""

        
    answered by 12.02.2018 / 11:00
    source