如何通过JSON的replacer函数对对象进行字符串化处理? [英] How to stringify objects through JSON's replacer function?

查看:104
本文介绍了如何通过JSON的replacer函数对对象进行字符串化处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

BAD = {
          "a": "2",
          "b": 1,
          "c": "Nexus",
          "d": "Alligator",
          "e": 5,
          "f": 1431807036,
          "g": {
                    "2": {
                            "w": 17,
                            "b": 5
                         }
               }
      }

console.log(JSON.stringify(BAD, ['a', 'b', 'c', 'd', 'e', 'g']));

http://jsfiddle.net/whv7x6xc/1/

只有字符串键abcdeg是不错的,但是存在一个问题.它忽略了分配给g的对象.

The keys a, b, c, d, e, and g are the only ones being stringified which is nice, but there is one problem. It's ignoring the object that is assigned to g.

但是,如果您这样做:console.log(JSON.stringify(BAD));它会显示正确的字符串化版本.

But, if you do: console.log(JSON.stringify(BAD)); it shows the proper stringified version.

wb以及动态和定期更改(来来去去),所以我不能仅将它们硬编码在其中.

w and b and dynamic and changed periodically (come and go) though, so I cannot just hard-code them in.

推荐答案

JSON替换器是递归的.这意味着它对遇到的 all 对象使用相同的数组.换句话说,它使用相同的值来映射BAD.g的值.由于Bad.g的值没有与您提供的键匹配的任何键,因此不会正确映射任何内容.这意味着我们必须在您的数组中添加"2".现在"2"也有一个具有不同键的对象.我们已经考虑了"b",因此现在我们只需要在您的数组中添加"w"即可.

JSON replacer is recursive. This then means it uses the same array for all objects it comes across. In other words, it uses the same values to map BAD.g's value. Since, Bad.g's value does not have any keys matching the ones you provided, nothing will get mapped properly. This means we have to add "2" to your array. Now "2" also has an object with different keys. We have already accounted for "b", so now we just need to add "w" to your array.

在为替换器提供数组时,最好将数组视为要映射的所有 键的列表.

When providing an array to the replacer, best to think of the array as a list of all the keys you want mapped.

演示: http://jsfiddle.net/dirtyd77/whv7x6xc/4/

console.log(JSON.stringify(BAD, ['a', 'b', 'c', 'd', 'e', 'g', '2', 'w']));

希望这会有所帮助,如果您有任何疑问,请告诉我.

Hope this helps and let me know if you have any questions.

这里也是文档

如果返回任何其他对象,则将该对象递归地字符串化为JSON字符串,并在每个属性上调用replacer函数,除非该对象是一个函数,在这种情况下,不会将任何内容添加到JSON字符串中.

If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.


对于动态键,您始终可以创建一个函数以推送到数组并将该数组用于白名单.这是一个示例:


In the case for dynamic keys, you can always create a function to push to an array and use that array for your whitelist. Here is an example:

演示: http://jsfiddle.net/dirtyd77/whv7x6xc/5/

var BAD = {
    "a": "2",
    "b": 1,
    "c": "Nexus",
    "d": "Alligator",
    "e": 5,
    "f": 1431807036,
    "g": {
        "2": {
            "w": 17,
            "b": 5
        }
    }
}

var whitelist = [];

iterate(BAD);

console.log(whitelist, JSON.stringify(BAD, whitelist));

function iterate(obj){
    for(var key in obj){
        // may have to do some checking to ignore any keys you don't care about
        whitelist.push(key);
        // if value is an object, will use this same function to push to whitelist array
        if(typeof obj[key] === 'object'){
            return iterate(obj[key]);
        }
    }
}


您也可以只使用现有的whitelist并在g键上附加键(假设它不是动态的):


You can also just use your existing whitelist and just append keys on your g key (given that isn't dynamic):

演示: http://jsfiddle.net/dirtyd77/whv7x6xc/6/

var whitelist = ['a', 'b', 'c', 'd', 'e', 'g'];

iterate(BAD.g);

console.log(whitelist, JSON.stringify(BAD, whitelist));

function iterate(obj){
    for(var key in obj){
        whitelist.push(key);
        if(typeof obj[key] === 'object'){
            return iterate(obj[key]);
        }
    }
}

这篇关于如何通过JSON的replacer函数对对象进行字符串化处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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