4

JavaScript Snippet – parseJSONC()

 2 years ago
source link: https://cwestblog.com/2022/02/05/javascript-snippet-parse-jsonc/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
JavaScript Snippet – parseJSONC() – Chris West's Blog

Last year I needed a way to be able to parse JSON with comments (also known as JSONC). With that in mind I wrote the following short solution which will essentially remove JavaScript-style comments and trailing commas from the specified JSONC string and then the native JSON.parse() function will parse the remaining string:

var parseJSONC = (function() { /** * @license Copyright 2021 - Chris West - MIT Licensed * @see https://gist.github.com/westc/32ae8971284b21dbc656926e7e210f5b * * Converts a JSONC (JSON with comments) to a JavaScript value. Allows for * trailing commas. * @param {string} code * The JSONC string that will be parsed and converted to a JS value. * @param {?(function(this:(Object|Array),string,any): any)=} reviver * If a function, this prescribes how the value originally produced by * parsing is transformed, before being returned. * @returns {*} * Returns the JS equivalent of the JSONC code that is given. */ function parseJSONC(code, reviver) { return JSON.parse( code.replace( /("(?:[^"\\]+|\\.)*")|\/\/[^\r\n]*|\/\*[^]*?\*\//g, get2ndOrSpaces ).replace( /("([^"\\]+|\\.)*")|,\s*(?=[\}\]])/g, get2ndOrSpaces ), reviver ); }

function get2ndOrSpaces(match, string) { return string || match.replace(/\S/g, ' '); } return parseJSONC; })();

Feel free to try this parseJSONC() function out yourself and let me know what you think. As always, happy coding! 😎


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK