Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a set of json data in javascript function?

I have a data set as below:

data = '{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}';

I am trying to make a function with the data set as its parameter, but the parameter wouldn't be read. Here is what I did:

function add(data) { alert(data); } add(data);

I only get [object Object],[object Object] ... What's the problem here? Thanks.

like image 699
D Kim Avatar asked Jun 02 '16 09:06

D Kim


2 Answers

The JSON string is wrong. It should be actually:

var data = '[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}]';

After that, you need to convert the JSON String into JSON object using the code below:

JSON.parse(d) /* d is the parameter of the method 'add()'  */

The alert will give you [object Object] output, as the variable data is itself the object. So if you want to see the whole json data, you need to console.log as:

console.log(JSON.parse(d));

Watch the demo.

like image 168
Shashank Avatar answered Nov 19 '22 14:11

Shashank


First of all, your data value is incorrect. Since it has 3 objects it has to be in an array. So, your data should be

data = '[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}]';

Then you need to use JSON.parse function to parse the string data into javascript object and then pass the object.

function add(data)
{ 
   alert(data);
   alert(data[0].a); //access 1ts objects a value
} 
var data = JSON.parse(data);
add(data);
like image 2
Karthik M R Avatar answered Nov 19 '22 16:11

Karthik M R