gpt4 book ai didi

javascript - jQuery JSON到字符串?

转载 作者:IT老高 更新时间:2023-10-28 12:43:04 25 4
gpt4 key购买 nike

我需要获取我的对象并将其作为表示 JSON 的字符串存储在一个变量中,而不是使用 JSON 字符串并使用 $.parseJSON。

(我正在处理的一个库需要一个格式错误的 JSON 类型,所以我需要弄乱它才能让它工作。)

最好的方法是什么?

最佳答案

编辑:您应该使用 Douglas Crockford 的 json2.js 库,而不是实现下面的代码。它提供了一些额外的功能和更好/更旧的浏览器支持。

从以下位置获取 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/

关于javascript - jQuery JSON到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3593046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com