Skip to content

Commit

Permalink
fix(devkit): make the JSON parser accepts trailing commas by default (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
vicb committed Jan 12, 2023
1 parent 59de87b commit 0d4833c
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/generated/devkit/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1705,7 +1705,7 @@ offsetFromRoot('apps/mydir/myapp/'); // returns "../../../"
**parseJson**<`T`\>(`input`, `options?`): `T`

Parses the given JSON string and returns the object the JSON content represents.
By default javascript-style comments are allowed.
By default javascript-style comments and trailing commas are allowed.

#### Type parameters

Expand Down
2 changes: 1 addition & 1 deletion docs/generated/packages/devkit/documents/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1705,7 +1705,7 @@ offsetFromRoot('apps/mydir/myapp/'); // returns "../../../"
**parseJson**<`T`\>(`input`, `options?`): `T`

Parses the given JSON string and returns the object the JSON content represents.
By default javascript-style comments are allowed.
By default javascript-style comments and trailing commas are allowed.

#### Type parameters

Expand Down
19 changes: 17 additions & 2 deletions packages/nx/src/utils/json.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,22 @@ describe('parseJson', () => {
`);
});

it('should throw when JSON has trailing commas', () => {
it('should allow trailing commas by default', () => {
expect(() =>
parseJson(
`{
"test": 123,
"nested": {
"test": 123,
"more": 456,
},
"array": [1, 2, 3,]
}`
)
).not.toThrow();
});

it('should throw when JSON has trailing commas if disabled', () => {
expect(() =>
parseJson(
`{
Expand All @@ -111,7 +126,7 @@ describe('parseJson', () => {
},
"array": [1, 2, 3,]
}`,
{ disallowComments: true, expectComments: true }
{ allowTrailingComma: false }
)
).toThrowErrorMatchingInlineSnapshot(`
"PropertyNameExpected in JSON at 6:6
Expand Down
4 changes: 3 additions & 1 deletion packages/nx/src/utils/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export interface JsonSerializeOptions {

/**
* Parses the given JSON string and returns the object the JSON content represents.
* By default javascript-style comments are allowed.
* By default javascript-style comments and trailing commas are allowed.
*
* @param input JSON content as string
* @param options JSON parse options
Expand All @@ -46,6 +46,8 @@ export function parseJson<T extends object = any>(
return JSON.parse(input);
} catch {}

options = { allowTrailingComma: true, ...options };

const errors: ParseError[] = [];
const result: T = parse(input, errors, options);

Expand Down

0 comments on commit 0d4833c

Please sign in to comment.