Skip to content

JSON parse works with type Buffer #44944

Description

lib Update Request

Configuration Check

My compilation target is ES2015 and my lib is the default.

Missing / Incorrect Definition

parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;

Sample Code

const object = JSON.parse(readFileSync("sample.json"));

Documentation Link

https://262.ecma-international.org/5.1/#sec-15.12.2
https://github.com/nodejs/node/blob/c41c09375b217d9daec614edb590147b14ff9b21/lib/buffer.js#L405

Suggestion

parse(text: string | Buffer, reviver?: (this: any, key: string, value: any) => any): any;

Activity

  1. IllusionMH commented on Jul 8, 2021

    @IllusionMH
    Contributor

    Same as #17203 and moreover Buffer is Node specific type and doesn't looks like it belongs to standard lib files.

  2. RyanCavanaugh commented on Jul 8, 2021

    @RyanCavanaugh
    Member

    This is just an implicit coercion, not anything JSON.parse does.

  3. qwelias commented on Dec 2, 2023

    @qwelias

    This is just an implicit coercion, not anything JSON.parse does.

    Literally false, see the spec step 1: Let jsonString be ? ToString(text) which explicitly converts text arg to it's string representation before doing anything else

  4. RyanCavanaugh commented on Dec 2, 2023

    @RyanCavanaugh
    Member

    I'm curious what you think an implicit coercion is?

  5. qraynaud commented on Sep 11, 2024

    @qraynaud

    Everything you said is true.

    But I still think the original comment has some point. It should not be a TS error to pass a Buffer to JSON.parse() since it’s pretty valid. Yes it’s an implicit coercion but it does make sense to use it there. Though I don’t know how you could patch this properly. It should still work in an ideal world.

  6. RyanCavanaugh commented on Sep 11, 2024

    @RyanCavanaugh
    Member

    If you have a raw Buffer you don't know if it's UTF-8, UTF-16, base64, etc.. Arguably the entire point of TS is to tell you when you're making assumptions like that.

    const b = Buffer.from("{}", "utf-16le");
    JSON.parse(b); // throws
  7. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions