我在一个使用AJAX访问的Java服务器应用程序中有一个字符串。它看起来如下所示:
var json = [{
"adjacencies": [
{
"nodeTo": "graphnode2",
"nodeFrom": "graphnode1",
"data": {
"$color": "#557EAA"
}
}
],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode1",
"name": "graphnode1"
},{
"adjacencies": [],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode2",
"name": "graphnode2"
}];
当字符串从服务器拉出来时,是否有一种简单的方法将其转换为活的JavaScript对象(或数组)?或者我必须手动分割字符串并手动构建我的对象?
JSON的全部意义在于JSON字符串可以不做任何事情就转换为本机对象。检查这个链接
你可以使用eval(字符串)或JSON.parse(字符串)。
但是eval是有风险的。从json.org:
The eval function is very fast.
However, it can compile and execute any JavaScript program,
so there can be security issues.
The use of eval is indicated when the source is trusted and competent.
It is much safer to use a JSON parser.
In web applications over XMLHttpRequest,
communication is permitted only to the same origin that
provide that page, so it is trusted.
But it might not be competent.
If the server is not rigorous in its JSON encoding,
or if it does not scrupulously validate all of its inputs,
then it could deliver invalid JSON text that could be carrying dangerous script.
The eval function would execute the script, unleashing its malice.
JSON的全部意义在于JSON字符串可以不做任何事情就转换为本机对象。检查这个链接
你可以使用eval(字符串)或JSON.parse(字符串)。
但是eval是有风险的。从json.org:
The eval function is very fast.
However, it can compile and execute any JavaScript program,
so there can be security issues.
The use of eval is indicated when the source is trusted and competent.
It is much safer to use a JSON parser.
In web applications over XMLHttpRequest,
communication is permitted only to the same origin that
provide that page, so it is trusted.
But it might not be competent.
If the server is not rigorous in its JSON encoding,
or if it does not scrupulously validate all of its inputs,
then it could deliver invalid JSON text that could be carrying dangerous script.
The eval function would execute the script, unleashing its malice.