Skip to content

Conversation

@devon-wolf
Copy link
Contributor

New option to remove newlines in empty arrays and objects

Fixes #15

This PR adds a new option, collapseEmpty, that can be passed when stringify is called. When collapseEmpty is true, empty arrays and empty objects within the output will not have indent characters inserted between their opening and closing brackets. The effect is that the empty brackets will appear next to each other on the same line as their key, even when space has been specified (which otherwise would lead to an indent with the space and a newline).

Example from the linked issue: output from stringify({ a: [], b: {} }, { space: 2 }) currently looks like:

{
  "a": [
  ],
  "b": {
  }
}

After these changes, stringify({ a: [], b: {} }, { collapseEmpty: true, space: 2 }) will look like:

{
  "a": [],
  "b": {}
}

collapseEmpty only matters when space has been specified, since the indent value otherwise is an empty string.

TODO: I'm happy to write the README entry for this once you've had a chance to review.

I do think there is a case to be made that this should be the default behavior, in order to maintain the same shape as JSON.stringify when given equivalent options. However, putting this behind a collapseEmpty option makes this behavior available without making a breaking change.

Note - I had initially checked if collapseEmpty was true inline in the places where it was needed, but this ran one unit past eslint's complexity threshold for the stringify function. I moved the grouping logic to its own closure to make the linter pass, but am happy to revert and adjust the linting rules instead if that's preferable.

Thanks for reviewing this, happy to make any changes!

New option to remove newlines in empty arrays and objects

Fixes ljharb#15
Copy link
Owner

@ljharb ljharb left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the delayed review, this looks good!

@devon-wolf
Copy link
Contributor Author

Excellent, thanks! Let me know if I need to do anything adjustment-wise.

@ljharb ljharb merged commit 59c4a2c into ljharb:main Apr 22, 2025
372 of 374 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Keep empty arrays & objects on same line

2 participants