Skip to content

JSON.stringify is not per spec / mismatches other engines on empty objects when padding is used #1564

@ChALkeR

Description

@ChALkeR

e.g.:

print(JSON.stringify([], undefined, 2)) // should be []
print(JSON.stringify({}, undefined, 2)) // should be {}

Spec:

25.5.2.6 SerializeJSONArray:

  1. If partial is empty, then
    a. Let final be "[]".

This happens regardless of state.[[Gap]] (and state.[[Indent]]) which affects only step 10. "Else".

25.5.2.5 SerializeJSONObject:

  1. If partial is empty, then
    a. Let final be "{}".

This also happens regardless of state.[[Gap]] (and state.[[Indent]]) which affects only only step 10. "Else" and elements in step 8 (of which there are none here).


I encountered this in snapshot testing with node:test-compatible plain JSON.stringify serialization (as opposed to Jest serializers)

Another place where this could be important is e.g. id generation, if smth does hash(JSON.srtringify(obj)) as a relatively common pattern. If those ids are expected to equal between client and server but aren't, things could break.
That said, that scenario is relatively unlikely to be using padding.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions