JavaScript: JSON stringify

Last update: 31 May 23:20
0
Students

JavaScript has a JSON.stringify() method to cast any value to a string. It works as follows:

JSON.stringify('hello'); // => "hello" - the quotes added to string values
JSON.stringify(true);    // => true    - boolean turns into string w/o quotes
JSON.stringify(5);       // => 5

const data = { hello: 'world', is: true, nested: { count: 5 } };
JSON.stringify(data); // {"hello":"world","is":true,"nested":{"count":5}}

JSON.stringify(data, null, 2); // with (null, 2) the function will insert two spaces before key
// keys receive quotation marks
// a comma is added at the end of each line if there is a value below
// {
//   "hello": "world",
//   "is": true,
//   "nested": {
//     "count": 5
//   }
// }

stringify.js

Implement and export as default a function like JSON.stringify(), but with the following differences:

  • keys and string values must be without quotes
  • the line ends with the value itself, w/o a comma

Syntax:

stringify(value[, replacer[, spacesCount]])

Parameters:

  • value
    • A value to transform into string
  • replacer, optional
    • A string to indent before key (a white space by default)
  • spacesCount, optional
    • A number of replacer characters used as white space (1 by default)
import stringify from './stringify.js';

stringify('hello'); // hello - the value is cast to a string, but doesn't have quotes
stringify(true);    // true
stringify(5);       // 5

const data = { hello: 'world', is: true, nested: { count: 5 } };
stringify(data); // the same as stringify(data, ' ', 1);
// {
//  hello: world
//  is: true
//  nested: {
//   count: 5
//  }
// }

stringify(data, '|-', 2);
// The character passed by the second argument is repeated as many times as specified by the third argument
// {
// |-|-hello: world
// |-|-is: true
// |-|-nested: {
// |-|-|-|-count: 5
// |-|-}
// }

Tips

  • to better grasp how JSON.stringify() works, try it with different data and parameters in the browser console
  • the tests go from simple to complex:
    • checking on primitive types
    • checking for "flat" data
    • checking for "nested" data

Implement the function from step to step, checking that the changes for more complex cases did not break the simpler ones.

For full access to the challenge you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests