Instead of going JSON a json string and using $.parseJSON, I need to take my object and store it in a variable as string representing JSON.
(我正在处理的一个库需要一个格式错误的JSON类型,所以我需要处理它才能让它工作.)
最好的方法是什么?
Instead of going JSON a json string and using $.parseJSON, I need to take my object and store it in a variable as string representing JSON.
(我正在处理的一个库需要一个格式错误的JSON类型,所以我需要处理它才能让它工作.)
最好的方法是什么?
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.
从以下位置获取json2.js文件:https://github.com/douglascrockford/JSON-js
// 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"}'
代码:http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/