Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/base/common/jsonc.ts
3291 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
// First group matches a double quoted string
7
// Second group matches a single quoted string
8
// Third group matches a multi line comment
9
// Forth group matches a single line comment
10
// Fifth group matches a trailing comma
11
const regexp = /("[^"\\]*(?:\\.[^"\\]*)*")|('[^'\\]*(?:\\.[^'\\]*)*')|(\/\*[^\/\*]*(?:(?:\*|\/)[^\/\*]*)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))|(,\s*[}\]])/g;
12
13
/**
14
* Strips single and multi line JavaScript comments from JSON
15
* content. Ignores characters in strings BUT doesn't support
16
* string continuation across multiple lines since it is not
17
* supported in JSON.
18
*
19
* @param content the content to strip comments from
20
* @returns the content without comments
21
*/
22
export function stripComments(content: string): string {
23
return content.replace(regexp, function (match, _m1, _m2, m3, m4, m5) {
24
// Only one of m1, m2, m3, m4, m5 matches
25
if (m3) {
26
// A block comment. Replace with nothing
27
return '';
28
} else if (m4) {
29
// Since m4 is a single line comment is is at least of length 2 (e.g. //)
30
// If it ends in \r?\n then keep it.
31
const length = m4.length;
32
if (m4[length - 1] === '\n') {
33
return m4[length - 2] === '\r' ? '\r\n' : '\n';
34
}
35
else {
36
return '';
37
}
38
} else if (m5) {
39
// Remove the trailing comma
40
return match.substring(1);
41
} else {
42
// We match a string
43
return match;
44
}
45
});
46
}
47
48
/**
49
* A drop-in replacement for JSON.parse that can parse
50
* JSON with comments and trailing commas.
51
*
52
* @param content the content to strip comments from
53
* @returns the parsed content as JSON
54
*/
55
export function parse<T>(content: string): T {
56
const commentsStripped = stripComments(content);
57
58
try {
59
return JSON.parse(commentsStripped);
60
} catch (error) {
61
const trailingCommasStriped = commentsStripped.replace(/,\s*([}\]])/g, '$1');
62
return JSON.parse(trailingCommasStriped);
63
}
64
}
65
66