您的位置:首页 > Web前端 > JavaScript

JS 中 JSON 与对象 的相互转换

2017-05-18 10:02 417 查看

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
解决方案如下:
<script>

$(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<len;i++){
str +='<li>'+
'<img class = "smallImg" src = "'+this.images[i].small+'"/>'+
'<img class = "bigImg" src = "'+this.images[i].big+'"/>'+
'</li>';

}
console.log(str)
$("#etakage").html(str);
}
}

</script>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: