如果我在JS中定义了一个对象:

var j={"name":"binchen"};

如何将对象转换为JSON?输出字符串应该是:

'{"name":"binchen"}'

当前回答

现有的JSON替换对我来说太多了,所以我写了自己的函数。这似乎是可行的,但我可能错过了一些边缘情况(在我的项目中不会出现)。并且可能不适用于任何已存在的对象,只适用于自制数据。

function simpleJSONstringify (obj) {
    var prop, str, val,
        isArray = obj instanceof Array;

    if (typeof obj !== "object")
        return false;

    str = isArray ? "[" : "{";

    function quote (str) {
        if (typeof str !== "string")
            str = str.toString ();

        // When the actual variable was a number, it was returning a number between quotation marks
        // return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"';

        // Now, we are verifing if is a number and, if it is, we remove the quotation marks
        str = str.match (/^\".*\"$/) ? str : '"' + str.replace (/"/g, '\\"') + '"';

        if (isNaN (str.replace (/^["]/, '').replace (/["]$/, '')))
            return str;
        else
            return str.replace (/^["]/, '').replace (/["]$/, '');
    }

    for (prop in obj) {
        if (!isArray) {
            // quote property
            str += quote (prop) + ": ";
        }

        // quote value
        val = obj [prop];
        str += typeof val === "object" ? simpleJSONstringify (val) : quote (val);
        str += ", ";
    }

    // Remove last colon, close bracket
    str = str.substr (0, str.length - 2) + ( isArray ? "]" : "}" );

    return str;
}

其他回答

现有的JSON替换对我来说太多了,所以我写了自己的函数。这似乎是可行的,但我可能错过了一些边缘情况(在我的项目中不会出现)。并且可能不适用于任何已存在的对象,只适用于自制数据。

function simpleJSONstringify (obj) {
    var prop, str, val,
        isArray = obj instanceof Array;

    if (typeof obj !== "object")
        return false;

    str = isArray ? "[" : "{";

    function quote (str) {
        if (typeof str !== "string")
            str = str.toString ();

        // When the actual variable was a number, it was returning a number between quotation marks
        // return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"';

        // Now, we are verifing if is a number and, if it is, we remove the quotation marks
        str = str.match (/^\".*\"$/) ? str : '"' + str.replace (/"/g, '\\"') + '"';

        if (isNaN (str.replace (/^["]/, '').replace (/["]$/, '')))
            return str;
        else
            return str.replace (/^["]/, '').replace (/["]$/, '');
    }

    for (prop in obj) {
        if (!isArray) {
            // quote property
            str += quote (prop) + ": ";
        }

        // quote value
        val = obj [prop];
        str += typeof val === "object" ? simpleJSONstringify (val) : quote (val);
        str += ", ";
    }

    // Remove last colon, close bracket
    str = str.substr (0, str.length - 2) + ( isArray ? "]" : "}" );

    return str;
}

要在Node JS中进行调试,可以使用util.inspect()。使用循环引用效果更好。

var util = require('util');
var j = {name: "binchen"};
console.log(util.inspect(j));

在angularJS

angular.toJson(obj, pretty);

obj: 要序列化为JSON的输入。

(可选): 如果设置为true, JSON输出将包含换行符和空格。如果设置为整数,则JSON输出每个缩进将包含相同数量的空格。

(默认值:2)

使用在json2.js中找到的JSON.stringify()或大多数现代浏览器中的本机。

JSON。Stringify (value, replace, space) value任何JavaScript值,通常是一个对象或数组。 替换一个可选参数,该参数决定对象的方式 对象的值是字符串化的。它可以是 函数或字符串数组。 空格指定缩进的可选参数 嵌套结构。如果省略它,文本将 打包时没有额外的空格。如果是数字, 它将指定每次缩进的空格数 的水平。如果它是一个字符串(如“\t”或“ ”), 它包含用于在每一层缩进的字符。

如果你想获得json属性值的字符串格式使用以下方式

var i = {"x":1}

var j = JSON.stringify(i.x);

var k = JSON.stringify(i);

console.log(j);

"1"

console.log(k);

'{"x":1}'