Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to json object in javascript [duplicate]

I have below javascript method. I try to get the id from the data parameter.

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

the first output line is receive {id:1}

but the second output line is undefined

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

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

I still got the same output. Why can't I get the id from the input parameter?

EDIT1

I changed the parameter name to be different with the function name as below:

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

but I still got the same output.

like image 955
Joey Yi Zhao Avatar asked Nov 19 '22 09:11

Joey Yi Zhao


1 Answers

Note: Strong word of caution. Just checking if this works, and it works. Do not use it in unexpected circumstances. Very dangerous!

One crazy thing is, you forgot the function keyword, in-front of the function name.

Trying with eval() for this:

function data(spark, d) {
  // console.log('receive ', d);
  eval("d = " + d);
  console.log(d.id);
}
data("", "{id: 5}");
like image 162
Praveen Kumar Purushothaman Avatar answered Jan 03 '23 23:01

Praveen Kumar Purushothaman