How to convert string to json object in javascript

I have a javascript method. I am trying to get id from data parameter.

data(spark, data){ console.log('receive ', data) console.log(data.id) } 

first output line receive {id:1}

but the second output line is undefined

then I tried the method below to convert a json string to an object:

 data(spark, data){ console.log('receive ', data) console.log(JSON.parse(JSON.stringify(data)).id) 

I have the same result. Why can't I get the identifier from the input parameter?

EDIT1

I changed the parameter name to be different from the function name, as shown below:

 data(spark, d){ console.log('receive ', d) console.log(JSON.parse(JSON.stringify(d)).id) } 

but I still get the same result.

+5
source share
3 answers

Note: A strong word of caution. Just check if this works and it works. Do not use it in unforeseen circumstances. Very dangerous!

One crazy thing, you forgot the function keyword, before the function name.

Try using eval() to do this:

 function data(spark, d) { // console.log('receive ', d); eval("d = " + d); console.log(d.id); } data("", "{id: 5}"); 
+2
source

Four answers:

  • Ask the server to send a properly formed JSON (with double quotes around the key names). This is the preferred solution.

  • Use the relaxed JSON parser. You can search and find such things on npm.

  • Use eval .

  • Do some string manipulation to enclose the id in double quotes so you can JSON.parse , or extract 1 , or whatever you want to do. This is the least preferred solution.

0
source

eval ("(+ + + + +))). id is all that is required

 function data(spark, data) { alert(eval("(" + data + ")").id); } data("", "{id:3}"); 
-2
source

Source: https://habr.com/ru/post/1261542/


All Articles