比如我有两个变量,我要将a转换成字符串,将b转换成JSON对象:
1 | var goods1= {"barcode":"122124545124","buyPrice":122,"color":"白色","id":7713,"isDelete":false,"lastedSaleTime":"2013-07-25 14:25:42","name":"黑色毛衣","page":0,"remark":"","rows":0,"showPrice":122,"size":"L","total":0,"type":"12112B","unit":"件"}; |
3 | var goods2= '{"barcode":"12454545454","buyPrice":133,"color":"黑色","id":7714,"isDelete":false,"lastedSaleTime":"2013-07-25
14:27:39","name":"春天幻想","page":0,"remark":"","rows":0,"showPrice":133,"size":"M","total":0,"type":"B","unit":"条"}' ; |
在Firefox,chrome,opera,safari,ie9,ie8等高级浏览器直接可以用JSON对象的stringify()和parse()方法。
JSON.stringify(obj)将JSON转为字符串。JSON.parse(string)将字符串转为JSON格式;
上面的转换可以这么写:
1 | var goods1= {"barcode":"122124545124","buyPrice":122,"color":"白色","id":7713,"isDelete":false,"lastedSaleTime":"2013-07-25 14:25:42","name":"黑色毛衣","page":0,"remark":"","rows":0,"showPrice":122,"size":"L","total":0,"type":"12112B","unit":"件"}; |
3 | var goods2= '{"barcode":"12454545454","buyPrice":133,"color":"黑色","id":7714,"isDelete":false,"lastedSaleTime":"2013-07-25
14:27:39","name":"春天幻想","page":0,"remark":"","rows":0,"showPrice":133,"size":"M","total":0,"type":"B","unit":"条"}' ; |
05 | var goods1ToStr=JSON.stringify(goods1); |
07 | var goods2ToObj=JSON.parse(goods2); |
09 | alert( typeof (goods1ToStr )); //string |
11 | alert( typeof (goods2ToObj )); //object |
JSON.stringify()
ie8(兼容模式),ie7和ie6没有JSON对象,不过
http://www.json.org/提供了一个json.js,这样ie8(兼容模式),ie7和ie6就可以支持JSON对象以及其stringify()和parse()方法;你可以在
https://github.com/douglascrockford/JSON-js上获取到这个js,一般现在用json2.js。
ie8(兼容模式),ie7和ie6可以使用eval()将字符串转为JSON对象,
1 | var c= '{"name":"Mike","sex":"女","age":"29"}' ; |
2 | var cToObj=eval( "(" +c+ ")" ); |
jQuery中也有将字符串转为JSON格式的方法
jQuery.parseJSON( json ),接受一个标准格式的 JSON 字符串,并返回解析后的 JavaScript (JSON)对象。当然如果有兴趣可以自己封装一个jQuery扩展,jQuery.stringifyJSON(obj)将JSON转为字符串