Created
November 6, 2015 01:10
-
-
Save LincolnBurrows/d8c8986a992cfc94b3b7 to your computer and use it in GitHub Desktop.
json 操作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var json = { | |
"age":24, | |
"name":"cst" | |
}; | |
//修改json中的age值,因为json中存在age属性 | |
json["age"] = 30; | |
//增加json中的sex属性,因为json中不存在sex属性 | |
json["sex"] = "M"; | |
//遍历json中的数据 | |
for(var key in json) | |
{ | |
try{ | |
var value = json[key]; | |
}catch(err){} | |
} | |
//删除json数据中的age属性 | |
delete json["age"]; | |
//定位数组中的json对象key属性等于value时在数组中的位置 | |
function indexJsonArrayByName(key,value,jsonArray) | |
{ | |
if(!jsonArray) | |
{ | |
return -1; | |
} | |
var index =-1; | |
for(var i=0;j<jsonArray.length;i++) | |
{ | |
var obj = jsonArray[i]; | |
if(obj[key]==value) | |
{ | |
index=i; | |
break; | |
} | |
} | |
return index; | |
} | |
var index = indexJsonArrayByName("key","value",array); | |
//根据查出的索引删除数组中的对象 | |
array.splice(index,count);//从index位置移除count个节点 | |
//JSON.stringify | |
var student = new Object(); | |
student.name ="Lanny"; | |
student.age = "25"; | |
student.location = "China"; | |
var json = JSON.stringify(student); | |
console.log(json); | |
JSON.parse(text, reviver)方法 | |
参数: | |
text必需。 一个有效的 JSON 字符串。 | |
reviver可选。 一个转换结果的函数。 将为对象的每个成员调用此函数。 如果成员包含嵌套对象,则先于父对象转换嵌套对象。 对于每个成员,会发生以下情况: | |
如果 reviver 返回一个有效值,则成员值将替换为转换后的值。 | |
如果 reviver 返回它接收的相同值,则不修改成员值。 | |
如果 reviver 返回 null 或 undefined,则删除成员 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment