简体   繁体   English

Javascript:将对象递归转换为字符串(包括子对象和数组),就好像在其周围有引号一样(与JSON.stringify不同)

[英]Javascript: Convert Object to String Recursively (including child objects and arrays) as if there were quotes around it (unlike JSON.stringify)

This question has been resolved. 这个问题已经解决。

Based on the answer from karuzo , I made a finalized version: 根据karuzo的回答,我完成了最终版本:

$['to'] = function ($a)
{
    $u = JSON.stringify(this); $w = this.typeof(); $x = $a.typeof();

    if ($x == 'Array')
    {
        if ($w == 'Object')
        {
            $y = []; this.keys().for(($l, $m, $n) =>
            {
                $y[$m] = [$l, this[$l]];
            });

            return $y;
        }

        else if ($w == 'Array')
        {
            return [].slice.call(this);
        }

        else if ($w == 'String')
        {
            return [this];
        };
    }

    else if ($x == 'Object')
    {
        if ($w == 'Object')
        {
            return this.to("").from({});
        }

        else if ($w == 'Array')
        {
            $y = {}; this.for(($l, $m, $n) =>
            {
                $l != {}._ ? $y[$m] = $l : null;
            });

            return $y;
        }

        else if ($w == 'String')
        {
            return {value: this};
        }
    }

    else if ($x == 'String')
    {
        if ($w == 'Object')
        {
            return JSON.stringify(this).replace(/\"([^(\")"]+)\":/g, '$1:');
        }

        else if ($w == 'Array')
        {
            return $u;
        }

        else if ($w == 'String' | $w == 'Number')
        {
            return this.toString();
        };
    }

    else
    {
        return this;
    };
}

This version is included directly in paxiom.js, the file which the code resides. 该版本直接包含在代码所在的文件paxiom.js中。 Some of the functions used in the above code are in the library. 上面的代码中使用的某些功能在库中。 I know this tends to get some viewers, so when the library's version #1 is finished, it will be available at https://hbms.github.io/-/paxiom.js 我知道这会吸引一些观众,因此,当库的版本1完成时,可以在https://hbms.github.io/-//paxiom.js上获得。

You can try: 你可以试试:

var obj = {a: "x", b: ["y"], c: {d: ["z"]}, e: [{f: "g"}]};

var objStr = JSON.stringify(obj).replace(/\"([^(\")"]+)\":/g,"$1:");

console.log(objStr);

Output: 输出:

{a:"x",b:["y"],c:{d:["z"]},e:[{f:"g"}]}

And you can eval() the resulting string: 您可以eval()得到的字符串:

var obj = eval(objStr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM