Question
Update JSON-like object that contains new lines and comments. I'm working on a Node application where I make a call to external API. I receive a response which looks exactly like this: { "data": "{\r\n // comment\r\n someProperty: '*',\r\n\r\n // another comment\r\n method: function(e) {\r\n if (e.name === 'something') {\r\n onSomething();\r\n }\r\n }\r\n}" } So as you can see it contains some comments, new line characters etc. I would like parse it somehow to a proper JSON and then update the method property with completely different function. What would be the best (working) way to achieve it? I've tried to use comment-json npm package, however it fails when I execute parse(response.data).Answer
<script> function get_response() { return JSON.stringify({ "data": "{\r\n // comment\r\n someProperty: '*',\r\n\r\n // another comment\r\n method: function(e) {\r\n if (e.name === 'something') {\r\n onSomething();\r\n }\r\n }\r\n}" }); } var resp = get_response() console.log("Response before formatting: " + resp); resp = resp.replace(/\/.*?\\r\\n/g, ""); resp = resp.replace(/\\r\\n/g, ""); console.log("Response after formatting: " + resp); console.log("And JSON.parse()") console.log(JSON.parse(resp)) </script>
Saturday, October 15, 2022
JavaScript RegEx Solved Interview Problem (Oct 2022)
Labels:
JavaScript,
Technology
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment