JSON.stringify can create Multi-line, formatted and filtered strings from JSON

Christian Heilmann - Oct 28 '22 - - Dev Community

You can use JSON.stringify() to turn a JSON object into a string.

let obj = {"a": 1, "b": 3, "c": "boo!"};
console.log(JSON.stringify(obj))
Enter fullscreen mode Exit fullscreen mode

This results in a single line string:

{"a":1,"b":3,"c":"boo!"}
Enter fullscreen mode Exit fullscreen mode

However, you can also set two optional parameters, a filtering array or callback method and an indentation parameter. Setting the indentation to four, for example, creates a multi line string with 4 spaces indentation:

let obj = {"a": 1, "b": 3, "c": "boo!"};
console.log(JSON.stringify(obj, false, 4))
Enter fullscreen mode Exit fullscreen mode

Output:

{
    "a": 1,
    "b": 3,
    "c": "boo!"
}
Enter fullscreen mode Exit fullscreen mode

If instead of spaces you want tabs, you can also defined the indentation parameter as a string:

let obj = {"a": 1, "b": 3, "c": "boo!"};
console.log(JSON.stringify(obj, false, "\t"))
Enter fullscreen mode Exit fullscreen mode

Output:

{
    "a": 1,
    "b": 3,
    "c": "boo!"
}
Enter fullscreen mode Exit fullscreen mode

Or any other string:

let obj = {"a": 1, "b": 3, "c": "boo!"};
console.log(JSON.stringify(obj, false, "xxx"))
Enter fullscreen mode Exit fullscreen mode

Output:

{
xxx"a": 1,
xxx"b": 3,
xxx"c": "boo!"
}
Enter fullscreen mode Exit fullscreen mode

You can define an array of keys you want to show to filter the outcome:

let obj = {"a": 1, "b": 3, "c": "boo!"};
console.log(JSON.stringify(obj, ['a','c'], 4))
Enter fullscreen mode Exit fullscreen mode

Output:

{
    "a": 1,
    "c": "boo!"
}
Enter fullscreen mode Exit fullscreen mode

And you can write a filtering callback function that gets applied to the JSON object. For example, to only allow for numbers to show:

const onlyNumbers = (key,value) => { 
  return (typeof value === 'string')  ? undefined : value 
}
let obj = {"a": 1, "b": 3, "c": "boo!"};
console.log(JSON.stringify(obj, onlyNumbers, 4))
Enter fullscreen mode Exit fullscreen mode

Output:

{
    "a": 1,
    "b": 3
}
Enter fullscreen mode Exit fullscreen mode

You can see more examples on MDN.

Whilst I like these options, it always feels weird to me when a method allows for different values to determine what to do. Having the replacer either be an array or a callback and the spaces option be a number or a string feels confusing. What do you think?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player