Skip to content

Commit 36ff72c

Browse files
committed
✨ Added support for JSON with comments;
1 parent c6741af commit 36ff72c

1 file changed

Lines changed: 53 additions & 1 deletion

File tree

Github_JSON_Dependencies_Linker/Github_JSON_Dependencies_Linker.user.js

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,59 @@
2828
isNuGet = location.pathname.endsWith('/project.json'),
2929
blobElm = document.querySelector('.blob-wrapper'),
3030
blobLineElms = blobElm.querySelectorAll('.blob-code > span'),
31-
pkg = JSON.parse(blobElm.textContent),
31+
pkg = (function() {
32+
// JSON parser could fail on JSON with comments;
33+
try {
34+
return JSON.parse(blobElm.textContent);
35+
} catch (ex) {
36+
// https://github.com/sindresorhus/strip-json-comments
37+
function stripJsonComments(str) {
38+
var currentChar;
39+
var nextChar;
40+
var insideString = false;
41+
var insideComment = false;
42+
var ret = '';
43+
for (var i = 0; i < str.length; i++) {
44+
currentChar = str[i];
45+
nextChar = str[i + 1];
46+
if (!insideComment && str[i - 1] !== '\\' && currentChar === '"') {
47+
insideString = !insideString;
48+
}
49+
if (insideString) {
50+
ret += currentChar;
51+
continue;
52+
}
53+
if (!insideComment && currentChar + nextChar === '//') {
54+
insideComment = 'single';
55+
i++;
56+
} else if (insideComment === 'single' && currentChar + nextChar === '\r\n') {
57+
insideComment = false;
58+
i++;
59+
ret += currentChar;
60+
ret += nextChar;
61+
continue;
62+
} else if (insideComment === 'single' && currentChar === '\n') {
63+
insideComment = false;
64+
} else if (!insideComment && currentChar + nextChar === '/*') {
65+
insideComment = 'multi';
66+
i++;
67+
continue;
68+
} else if (insideComment === 'multi' && currentChar + nextChar === '*/') {
69+
insideComment = false;
70+
i++;
71+
continue;
72+
}
73+
if (insideComment) {
74+
continue;
75+
}
76+
ret += currentChar;
77+
}
78+
return ret;
79+
}
80+
// Strip out comments from the JSON and try again;
81+
return JSON.parse(stripJsonComments(blobElm.textContent));
82+
}
83+
})(),
3284
dependencyKeys = [
3385
'dependencies',
3486
'devDependencies',

0 commit comments

Comments
 (0)