转自:
https://www.jianshu.com/p/6501b0f3124f
- 直接定义json
var json = {"name": "小明", "age": 12};
console.log(json);
- json 转 String
var str = JSON.stringify(json);
console.log(str);
- String 转 Json
json = JSON.parse(str);
console.log(json)
- 添加新的字段
// 方式1
json.sex = '女';
// 方式2
var id = 'id';
json[id] = '123';
console.log(json)
- 判断字段是否存在
console.log(json.hasOwnProperty(id))
- 删除字段
方式1
delete json.id;
console.log(json);
方式2
delete json[id];
console.log(json);
- 添加JsonArray
var array = [{"name": "小李", "age": 20}];
console.log(array);
array.push(json);
console.log(array);
- 遍历JsonArray
for (var item in array) {
console.log(array[item].name)
}
- 删除array中的一项
array.splice(1)
完整代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript">
var json = {"name": "小明", "age": 12};
console.log(json);
var str = JSON.stringify(json);
console.log(str);
json.sex = '女';
var id = 'id';
json[id] = '123';
console.log(json)
console.log(json.hasOwnProperty(id))
delete json.id;
console.log(json);
id = 'id';
json[id] = '123';
console.log(json);
delete json[id];
console.log(json);
var array = [{"name": "小李", "age": 20}];
console.log(array);
array.push(json);
console.log(array);
for (var item in array) {
console.log(array[item].name)
}
array.splice(1)
console.log(array)
</script>
</body>
</html>
0人点赞