首页 > Web开发 > 详细

JS 中Json常用操作

时间:2019-09-12 22:40:23      阅读:81      评论:0      收藏:0      [点我收藏+]

转自:

https://www.jianshu.com/p/6501b0f3124f

 

  1. 直接定义json
   var json = {"name": "小明", "age": 12};
   console.log(json);
  1. json 转 String
    var str = JSON.stringify(json);
   console.log(str);
  1. String 转 Json
json = JSON.parse(str);
console.log(json)
  1. 添加新的字段
  // 方式1
   json.sex = ‘女‘;
  // 方式2
   var id = ‘id‘;
   json[id] = ‘123‘;
   console.log(json)
  1. 判断字段是否存在
console.log(json.hasOwnProperty(id))
  1. 删除字段
方式1
delete json.id;
console.log(json);
方式2
delete json[id];
console.log(json);
  1. 添加JsonArray
var array = [{"name": "小李", "age": 20}];
console.log(array);
array.push(json);
console.log(array);
  1. 遍历JsonArray
for (var item in array) {
       console.log(array[item].name)
   }
  1. 删除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人点赞
 

JS 中Json常用操作

原文:https://www.cnblogs.com/sharpest/p/11514791.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!