The JSON.stringify()
method
accepts three arguments -
-
The value to be converted into a JSON string.
-
Either an array or a function
that can be used to filter
the properties of the first argument
and
include only those properties
in the JSON string.
-
Either the number of spaces
or
the string to be used for
indentation of the JSON string.
In the example given above,
we pass the array
["firstName", "lastName"]
as the second argument to JSON.stringify()
.
This filters the output
to include only the properties
whose keys are mentioned in the array.
In the example given above,
we pass the function checkIfStringValue
as the second argument to JSON.stringify()
.
This filters the output
to include only the properties
whose values are not of the type "string".
The function passed as the second argument -
checkIfStringValue
,
is invoked for
each property of the object.
For each invocation,
two arguments key
and value
are passed.
In the above example,
JSON.stringify(user, checkIfStringValue, 5)
has a third argument 5
.
The third argument indicates
the number of spaces to be used
for indentation of the JSON string.
To add indentation to result
of JSON.stringify
without the second argument
that filters the properties,
we can pass null
as the
second argument.
It is possible to indent the JSON string
returned by JSON.stringify
using a specific string,
as shown in the example below.