What's the difference in using toString() compared to JSON.stringify()?

前端 未结 4 869
北荒
北荒 2020-12-08 04:28

In both the cases I get in output the content of the object:

alert(JSON.stringify(obj));

or

alert(obj.toString());
<         


        
4条回答
  •  鱼传尺愫
    2020-12-08 05:13

    You can use the replacer and space parameter in JSON.stringify, passing the replacer argument as a function you can modify the object and space parameter helps you to give extra space before every key value pair.

    const replacer = (key, value) => {
            // Filtering out properties
            if (typeof value === 'number') {
                return 1;
            }
            return value;
        },
    
        foo = {
            country: 'India',
            state: 'Gujarat',
            district: 45,
            cm: 'car',
            am: 7
        },
    
        result = JSON.stringify(foo, replacer);
    
    console.log(result) // {"country":"India","state":"Gujarat","district":1,"cm":"car","am":1}
    

    Space argument -

    const obj = { a : 1, b:2};
    
    const obj_str = JSON.stringify(obj, null, '     ');// '\t' gives one tab 
    
    console.log(obj_str)
    

    For more details you can visit this link.

提交回复
热议问题