Skip to content

Improve empty container detection logic in formatJsonString function #257

Description

@coderabbitai

Issue Description

The empty container detection logic in the formatJsonString function (lines 78-91 in src/index.ts) currently checks if the result string ends with { or [ directly, which can fail if there is trailing whitespace.

Current Code

const isEmptyContainer = result.endsWith("{") || result.endsWith("[");

Problem

The current logic might fail for formatted JSON that already has whitespace, leading to incorrect formatting behavior.

Suggested Fix

Replace the current check with one that trims trailing whitespace:

// Look back to find the last structural character, ignoring whitespace
const trimmedResult = result.trimEnd();
const isEmptyContainer = trimmedResult.endsWith("{") || trimmedResult.endsWith("[");

Context

This issue was identified during code review to ensure the JSON formatting function handles all edge cases correctly, especially when dealing with whitespace around structural characters.

Backlinks

Requested by: @jellydn

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions