I’m parsing some data using a type class in my controller. I’m getting data as follows:
JavaScript
x
29
29
1
{
2
"data":{
3
"userList":[
4
{
5
"id":1,
6
"name":"soni"
7
}
8
]
9
},
10
"status":200,
11
"config":{
12
"method":"POST",
13
"transformRequest":[
14
null
15
],
16
"transformResponse":[
17
null
18
],
19
"url":"/home/main/module/userlist",
20
"headers":{
21
"rt":"ajax",
22
"Tenant":"Id:null",
23
"Access-Handler":"Authorization:null",
24
"Accept":"application/json, text/plain, */*"
25
}
26
},
27
"statusText":"OK"
28
}
29
I tried to store the data like this
JavaScript
1
3
1
var userData = _data;
2
var newData = JSON.parse(userData).data.userList;
3
How can I extract the user list to a new variable?
Advertisement
Answer
The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.
You can test this yourself, e.g. in Chrome’s console:
JavaScript
1
9
1
new Object().toString()
2
// "[object Object]"
3
4
JSON.parse(new Object())
5
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
6
7
JSON.parse("[object Object]")
8
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
9
JSON.parse()
converts the input into a string. The toString()
method of JavaScript objects by default returns [object Object]
, resulting in the observed behavior.
Try the following instead:
JavaScript
1
2
1
var newData = userData.data.userList;
2