Skip to content

Handling invalid unicode escapes #192

Closed

Description

@GULPF

Background: json5/json5-spec#12

JSON5.parse uses the ES6 behavior and accepts invalid Unicode sequences like "\uDEAD". However, this is not the case for the CLI. The CLI instead outputs U+FFFD (the replacement character). This probably happens because of Node trying to ensure that the output is valid UTF-8. I think it's best if these codepoints are escaped in the output, so that "\uDEAD" generates the escaped output "\uDEAD".

Activity

  1. jordanbtucker commented on Mar 4, 2019

    @jordanbtucker
    Member

    I wasn't able to reproduce this issue. Can you please provide some code that demonstrates this?

  2. self-assigned this
    on Mar 4, 2019
  3. GULPF commented on Mar 4, 2019

    @GULPF
    Author

    input.json5 contains "\uDEAD". After running json5 input.json5 -o output.json, output.json contains the following bytes (in hex): 22 EF BF BD 22, which is a string only containing the replacement character.

  4. jordanbtucker commented on Mar 6, 2019

    @jordanbtucker
    Member

    Thanks for the example. That clarified the issue for me.

    Your assumption about why this happens is correct. Since both JSON and JSON5 allow for invalid code unit sequences, the CLI should preserve them, however this would be a breaking change. The best approach may be to add a CLI flag in v2.2 that escapes invalid code point sequences. In v3.0 we can make that behavior the default and replace the CLI flag with one that replaces invalid code unit sequences with \uFFFD.

  5. added this to the v3.0.0 milestone on Feb 23, 2022
  6. bybraveHQ commented on Jul 5, 2026

    @bybraveHQ
    Collaborator

    Fixed in the maintained fork @bybrave/json5: stringify now escapes lone surrogates (an unpaired high or low surrogate code unit) as \uXXXX instead of emitting an invalid string that reads back as U+FFFD. Valid surrogate pairs (emoji etc.) are left intact and still round-trip. npm i @bybrave/json5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions