JS 中 JSON 与对象 的相互转换

您所在的位置:网站首页 json 转为对象 JS 中 JSON 与对象 的相互转换

JS 中 JSON 与对象 的相互转换

2024-07-11 22:45| 来源: 网络整理| 查看: 265

1、Json 应用现状 

客户端和服务端的数据交换以一定的格式进行,目前,这种数据格式以xml和Json为主。Json是JavaScript Object Notation的简写,采用JavaScript引擎自然匹配的格式,因此相较于xml更为易读,传输字节数也要远小于xml格式,相较之下,更受青睐,应用广泛。

2、转换方式

  前端开发中,数据传输格式中有一部分以JSON格式进行传递,比如Ajax,需要JSON和JS对象的相互转换。

      2.1 JSON转JS对象

两种方式:

   1、JS自带的eval()函数;

       2、JSON.parse(str); //str为变量,即json字符串;

var data = '{'+ '"name":"iphone plus",'+ '"price":"666",'+ '"description":"手机中的战斗机",'+ '"youhuijia":"555",'+ '"sum":"333",'+ '"image":['+ '{'+ '"small":"../images/s11.jpg",'+ '"big":"../images/s11.jpg"'+ '},'+ '{'+ '"small":"../images/s12.jpg",'+ '"big":"../images/s12.jpg"'+ '},'+ '{'+ '"small":"../images/s13.jpg",'+ '"big":"../images/s13.jpg"'+ '}'+ ']'+ '}'; console.log(data); var jsonObj1 = JSON.parse(data); //使用JSON.parse() 将JSON字符串转为JS对象; console.log(jsonObj1); var jsonObj2 = eval('(' + data + ')'); //使用eval() 将JSON字符串转为JS对象; console.log(jsonObj2);

  2.2JS对象转JSON 一种方式:JSON.stringify(obj) var json = {"name":"iphone","price":666}; //创建对象; var jsonStr = JSON.stringify(json); //转为JSON字符串 console.log(jsonStr);

          2.3 其他方式(未验证)      JS对象转JSON :Object.toJSONString()      JSON转JS对象:String.parseJSON()       有条件的同行可以验证一下。 3、实例应用 前几日在知乎上看到一个帖子,请教JSON转JS对象的问题,链接如下:                 https://www.zhihu.com/question/57309421?utm_source=qq&utm_medium=social 解决方案如下: $(function(){ //测试验证 //console.log(data.name); console.log(transformProduct(data)); }); var data = '{'+ '"name":"iphone plus",'+ '"price":"666",'+ '"description":"手机中的战斗机",'+ '"youhuijia":"555",'+ '"sum":"333",'+ '"image":['+ '{'+ '"small":"../images/s11.jpg",'+ '"big":"../images/s11.jpg"'+ '},'+ '{'+ '"small":"../images/s12.jpg",'+ '"big":"../images/s12.jpg"'+ '},'+ '{'+ '"small":"../images/s13.jpg",'+ '"big":"../images/s13.jpg"'+ '}'+ ']'+ '}'; function transformProduct(data){ data = JSON.parse(data); var product = new Product(); product.name = data.name; product.description = data.description; product.youhuijia = data.youhuijia; product.normalPrice = data.price; product.buySum = data.sum; product.images = data.image; product.bindDomImage(); return product; } function Product(){ this.name = ''; this.description = ''; this.normalPrice = 0; this.youhuijia = 0; this.buySum = 0; this.images = []; } Product.prototype = { bindDomImage:function(){ var str = ''; for(var i = 0,len = this.images.length;i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3