近来在做前端的时候,需要用到json,以前没怎么用过,临时报佛脚
记录遇到的问题:
在js中接收返回值,比如value之后,把json转换成对象
var json = JSON.parse(value);
下面是论坛里面的大神,帮我写的两种搜索json串的方法,在这里记下来,以免忘记
第一种(功能类似select age from json where id = 1):
var json = [
{
"id": "1",
"num":"123",
"age": "23"
},
{
"id": "2",
"num":" 234",
"age":"20"
}
];
function getItem(arr,n,v) {
for (var i = 0; i < arr.length; i++)
if (arr[i][n]==v)
return arr[i];
}
alert(getItem(json,"id","2").age);
alert(getItem(json,"num","123").age);
第二种(功能类似select age from json where id = 1 and num = 123):
var json = [
{
"id": "1",
"num":"123",
"age": "23"
},
{
"id": "2",
"num":"234",
"age":"20"
}
];
function getItem(arr,obj) {
arrFor: for (var i = 0; i < arr.length; i++) {
for (var n in obj)
if (arr[i][n]!=obj[n])
continue arrFor;
return arr[i];
}
}
alert(getItem(json,{"id":"2","num":"234"}).age);
因为json是无序的,所以,顺序不同不影响方法执行!