jquery json到字符串? [英] jquery json to string?
问题描述
我不需要从json字符串中使用$ .parseJSON,而是需要获取我的对象并将其作为表示json的字符串存储在变量中。
(A我正在处理的库需要一个格式错误的json类型,所以我需要弄乱它才能使它工作。)
最好的方法是什么?
编辑你应该使用Douglas Crockford的json2.js库而不是实现下面的代码。它提供了一些额外的功能和更好/更旧的浏览器支持。
从以下网址获取json2.js文件: https: @g 来自的代码: http://www.sitepoint.com/blogs/2009 / 08/19 / javascript-json-serialization / Instead of going from a json string and using $.parseJSON, I need to take my object and store it in a variable as string representing json. (A library I'm dealing with expects a malformed json type so I need to mess around with it to get it to work.) What's the best way to do this? Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support. Grab the json2.js file from: https://github.com/douglascrockford/JSON-js
//实现JSON.stringify序列化
JSON.stringify = JSON.stringify || function(obj){
var t = typeof(obj);
if(t!=object|| obj === null){
//简单数据类型
if(t ==string)obj =''+ obj + '';
return String(obj);
}
else {
//递归数组或对象
var n,v,json = [],arr =(obj&& obj.constructor == Array) ;
for(n in obj){
v = obj [n]; t = typeof(v);
if(t ==string)v =''+ v +'';
else if(t ==object&& v!== null)v = JSON.stringify(v);
json.push((arr?:''+ n +':')+ String(v));
}
return(arr?[:{)+ String(json)+(arr?]:});
}
};
var tmp = {one:1,two:2};
JSON.stringify(tmp); //'{one:1,two:2}'
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"'+obj+'"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof(v);
if (t == "string") v = '"'+v+'"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'
Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/
这篇关于jquery json到字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!