Hone logo
Hone
Problems

Pretty JSON Output in Jest

When debugging tests, especially those involving complex data structures like JSON, default Jest output can be difficult to parse. This challenge asks you to create a helper function that formats JSON data in a "pretty" (human-readable) way, making it easier to inspect within your Jest test reports.

Problem Description

You need to implement a TypeScript function named prettyPrintJson that takes a JavaScript object or array and returns a nicely formatted JSON string. This function will be used within Jest tests to improve the readability of assertion failures or console.log outputs during debugging.

Key Requirements:

  • The function should accept any valid JavaScript object or array that can be serialized to JSON.
  • The output JSON string should be indented with a specified number of spaces for each level of nesting.
  • The function should handle nested objects and arrays correctly.
  • The function should be written in TypeScript.

Expected Behavior:

  • Given an input object, it should return a string representing that object in pretty-printed JSON format.
  • Given an input array, it should return a string representing that array in pretty-printed JSON format.

Edge Cases to Consider:

  • Empty objects {} and arrays [].
  • Objects with null or undefined values (though undefined properties are typically omitted in JSON stringification).
  • Deeply nested structures.

Examples

Example 1:

Input:
{
  name: "Hone",
  role: "AI Coding Mentor",
  skills: ["TypeScript", "JavaScript", "Problem Solving"],
  details: {
    version: 1.0,
    active: true
  }
}

Output:
{
  "name": "Hone",
  "role": "AI Coding Mentor",
  "skills": [
    "TypeScript",
    "JavaScript",
    "Problem Solving"
  ],
  "details": {
    "version": 1,
    "active": true
  }
}

Explanation: The input object is converted to a JSON string with an indentation of 2 spaces, making its structure clear.

Example 2:

Input:
[
  { id: 1, value: "apple" },
  { id: 2, value: "banana" }
]

Output:
[
  {
    "id": 1,
    "value": "apple"
  },
  {
    "id": 2,
    "value": "banana"
  }
]

Explanation: An array of objects is also pretty-printed with proper indentation.

Example 3:

Input: {}
Output: {}

Explanation: An empty object is returned as an empty JSON object string.

Example 4:

Input: []
Output: []

Explanation: An empty array is returned as an empty JSON array string.

Constraints

  • The indentation level should be configurable, defaulting to 2 spaces if not specified.
  • The function should be efficient enough for typical Jest test runs.
  • The input will always be a valid JavaScript object or array.

Notes

Consider using built-in JavaScript methods for JSON manipulation. Think about how you can achieve the indentation and formatting requirements. This function is intended to complement Jest's built-in capabilities for assertion messages.

Loading editor...
typescript