JS 中Json常用操作

转自:

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人点赞
 
技术杂文

 

 

转载于:https://www.cnblogs.com/sharpest/p/11514791.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值