I want to convert a JSON to a javascript object [duplicated]

1

I want to convert a JSON to a javascript object but it gives me this error:

  

Uncaught SyntaxError: Unexpected token or in JSON at position 1 at   JSON.parse () at convertJsontoObjetoJS   (Test_JSON-serializacion.js: 23) at onload (Text_html.html: 15)

I do not know why I get that, here's the code:

var JSONString2 = {"altura": 1.20, "edad": 5, "colorOjos": "cafe"};

var objetoJS = JSON.parse(JSONString2);
console.log(objetoJS);
for (i in objetoJS) {
    document.write("Propiedad " + i + " : " + objetoJS[i] + "<br>");
}
    
asked by Giafir Anthony Fenco Garnique 11.12.2018 в 02:22
source

2 answers

0

The error is that you are trying to interpret a javascript object as a JSON.

The JSON.parse function receives as parameter a chain, and what you were sending was already an object.

that you check it easy observing that:

var JSONString2 = {
  "altura": 1.20,
  "edad": 5,
  "colorOjos": "cafe"
};
console.log(typeof JSONString2);
var JSONString2 = '{
  "altura": 1.20,
  "edad": 5,
  "colorOjos": "cafe"
}';
console.log(typeof JSONString2);

Therefore, your corrected example is now:

var JSONString2 = '{"altura": "1.20", "edad": "5", "colorOjos": "cafe"}';
var objetoJS = JSON.parse(JSONString2);
console.log(objetoJS);

for (i in objetoJS) {
  document.write("Propiedad " + i + " : " + objetoJS[i] + "<br>");
}
    
answered by 11.12.2018 / 03:33
source
1

To enter the data of a Json.

    let JSONString2 = {
      "altura": 1.20,
      "edad": 20,
      "colorOjos": "cafe"
    }

    console.log(JSONString2.edad)

% another way to walk the json

for (let dato in JSONString2){
  console.log(JSONString2[dato])
}
    
answered by 11.12.2018 в 03:11