Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JSON]: make parsing lenient by default and display better errors #14203

Closed
1 task done
vicb opened this issue Jan 6, 2023 · 3 comments · Fixed by #14317
Closed
1 task done

[JSON]: make parsing lenient by default and display better errors #14203

vicb opened this issue Jan 6, 2023 · 3 comments · Fixed by #14317

Comments

@vicb
Copy link
Contributor

vicb commented Jan 6, 2023

Description

Nx uses JSON.parse

It has several pain points:

  • It does not support trailing comma - while TS is happy with them i.e. when reading tsconfig.json,
  • The error messages are helpless: Error in JSON at position 1234

It should be easy to switch parser.

Typescript uses https://www.npmjs.com/package/jsonc-parser (as a devDependency)

https://www.npmjs.com/package/parse-json seems to have nice error messages.

The hard part for this issue is probably to pick the right parser...

@vicb
Copy link
Contributor Author

vicb commented Jan 11, 2023

Oh thanks!

export function parseJson<T extends object = any>(
input: string,
options?: JsonParseOptions
): T {
try {
return JSON.parse(input);
} catch {}
const errors: ParseError[] = [];
const result: T = parse(input, errors, options);
if (errors.length > 0) {
const { error, offset } = errors[0];
throw new Error(
`${printParseErrorCode(error)} in JSON at position ${offset}`
);
}
return result;

Sorry I stopped parsing the code at return JSON.parse(input); :(

Because we already use jsonc-parser I wonder if:

  • it would make sense to make parseJson lenient by default (allow comment and trailing commas),
  • it woud be possible to display better error message than Error in JSON at position 1234 - it wonder if getLocation could help here.

@vicb vicb changed the title Switch to better JSON parser [JSON]: make parsing lenient by default and display better errors Jan 11, 2023
@github-actions
Copy link

github-actions bot commented Mar 3, 2023

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 3, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants