You can use a method to easy parse your data.
with hasOwnProperty
Fiddle : JSFiddle example
質問
I am getting the response from backend, it return the json data.
But I need to pass the object separately to "handlebars.js
" - templates.
In this case, how do I iterate the json response and filter the data what I want?
My sample data :
{
"username":"xxxx",
"name":"yyyyy",
"allLocales":[
{ "name":"Afrikaans"
},
{ "name":"Albanian"
} "name":"Arabic"
],
"userLocales":[
{ "name":"English (US)"
},
{ "name":"Swedish"
}
],
"message":"New massage will be here"
}
How can I get the var username = {"username":"xxxx"}
, and
var nantions = "allLocales":[
{ "name":"Afrikaans"
},
{ "name":"Albanian"
} "name":"Arabic"
]
and like so..?
解決
他のヒント
Just reference the respective part of the object created by the JSON.
var nantions = jsonObj[ 'allLocales' ];
If you need to parse the JSON beforehand, use JSON.parse()
:
var jsonObj = JSON.parse( json );
EDIT
If you need the username
really as an object, I think you are left with this:
var username = { 'username': jsonObj['username'] };
first please assign the sample data to a variable
var json_test = {
"username":"xxxx",
"name":"yyyyy",
"allLocales":[
{ "name":"Afrikaans"
},
{ "name":"Albanian"
},
{ "name":"Arabic"
}
],
"userLocales":[
{ "name":"English (US)"
},
{ "name":"Swedish"
}
], "message":"New massage will be here" };
after this if you want to access username the you should write like this
var username = json_test['username'];
var nantions = json_test['allLocales'];
You can access the properties of an object with a simple dot-notation:
objectName.propertyName
For example, in your case
var username = obj.username; // xxxx
var nantions = obj.allLocales; // array of Object
More details here: Working with objects