Convert JS object to JSON string

后端 未结 27 3144
庸人自扰
庸人自扰 2020-11-22 00:43

If I defined an object in JS with:

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

How can I convert the object to JSON? The output string should be:

27条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 01:42

    The existing JSON replacements where too much for me, so I wrote my own function. This seems to work, but I might have missed several edge cases (that don't occur in my project). And will probably not work for any pre-existing objects, only for self-made data.

    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();
            return str.match(/^\".*\"$/) ? str : '"' + str.replace(/"/g, '\\"') + '"'
        }
    
        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;
    }
    

提交回复
热议问题