In: Computer Science
JS
Suppose you have an object named obj. How do you serialize it to a JSON string with each level indented two spaces? This action is the inverse of JSON.parse.
Method 1:
You need json2.js search in github
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
2. Method 2:
In angularJS
angular.toJson(obj, pretty);
obj: Input to be serialized into JSON.
pretty(optional):
If set to true, the JSON output will contain newlines and
whitespace. If set to an integer, the JSON output will contain that
many spaces per indentation.
I have used the angular approach previously.