Skip to content

SyntaxNode .toJSON() does not behave as expected #246

@maddrag0n

Description

@maddrag0n

SyntaxNode.toJSON() does not result in the JSON representable version of the SyntaxNode

Example

const parser = new TreeSitter();
parser.setLanguage(TreeSitterTypescript.tsx as Language);

const tree = parser.parse('import type { PropsWithChildren } from \'react\';\n\nexport function MyComponent({ children }: PropsWithChildren<{}>) {\n  return (\n    <div>{children}</div>\n  );\n}');

/*
this will not return a stringified JSON representation of the actual rootNode, but some parsed meta:

{
  "0": 62244512,
  "1": 24576,
  "2": 0,
  "3": 0,
  "4": 0,
  "5": 0,
  "tree": {
    "input": "import type { PropsWithChildren } from 'react';\n\nexport function MyComponent({ children }: PropsWithChildren<{}>) {\n  return (\n    <div>{children}</div>\n  );\n}",
    "language": { … }
  }
}

*/
JSON.stringify(tree.rootNode, undefined, '  ');

/* this returns a stringified JSON array of the same parsed meta

[
  {
    "0": 14798304,
    "1": 24576,
    "2": 0,
    "3": 0,
    "4": 0,
    "5": 0,
    "tree": {
      "input": "import type { PropsWithChildren } from 'react';\n\nexport function MyComponent({ children }: PropsWithChildren<{}>) {\n  return (\n    <div>{children}</div>\n  );\n}",
      "language": { … }
    }
  },
  {
    "0": 14734976,
    "1": 24576,
    "2": 98,
    "3": 2,
    "4": 0,
    "5": 0,
    "tree": {
      "input": "import type { PropsWithChildren } from 'react';\n\nexport function MyComponent({ children }: PropsWithChildren<{}>) {\n  return (\n    <div>{children}</div>\n  );\n}",
      "language": { … }
    }
  }
]

*/
JSON.stringify(tree.rootNode.children, undefined, '  ');

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