jquery json到字符串? [英] jquery json to string?

查看:188
本文介绍了jquery json到字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



最好的方法是什么?

解决方案

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



从以下网址获取json2.js文件: https: @g




//实现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}'

来自的代码: 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


// 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆