Skip to content

diffJson throws on truthy, non-callable toJSON #699

Description

@aforemendude

diffJson would call toJSON when it's truthy, even if it's not callable. This can cause diffJson to throw on valid JSON objects. JSON.stringify only calls toJSON if it's callable.

Reproduced on the latest v9.0.0. Happening to the latest master as well.

Reproduction:

https://github.com/aforemendude/bugs-reproduction/tree/main/jsdiff-non-callable-tojson

import { diffJson } from 'diff'

const oldObject = JSON.parse('{"toJSON":"old"}')
const newObject = JSON.parse('{"toJSON":"new"}')

try {
  console.log(diffJson(oldObject, newObject))
} catch (error) {
  console.log(`${error.name}: ${error.message}`)
}

Output:

TypeError: obj.toJSON is not a function

Activity

  1. ExplodingCabbage commented on Aug 12, 2026

    @ExplodingCabbage
    Collaborator

    Hmm, yeah. Seems to happen back in v5.0.0 (back before I took over maintenance) too. Surely simple to fix but will just have to do a bit of reading to figure out exactly what the correct fix is (is there a clean way in JS to check if something is a callable? Hmm...).

  2. aforemendude commented on Aug 12, 2026

    @aforemendude
    Author

    It's a little tricky to get the callable check to match JSON.stringify exactly, but typeof obj.toJSON === "function" should cover pretty much all use cases.

    The only edge case I can think of is document.all, where its typeof is "undefined", but it's callable.

  3. ExplodingCabbage commented on Aug 12, 2026

    @ExplodingCabbage
    Collaborator

    Yeah, that's what I concluded. The JSON.stringify spec indicates it looks for the internal [[Call]] method, and the typeof spec indicates that's also what typeof looks for (after exhausting various other cases that are all non-callable besides the ridiculous document.all edge case).

    https://stackoverflow.com/a/72322002/1709587 further suggests to me that typeof really is the intended/idiomatic way to check for callables and that there's basically no alternative.

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions