Home > OS >  Update JSON-like object that contains new lines and comments
Update JSON-like object that contains new lines and comments

Time:10-14

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).

CodePudding user response:

Try using this

const r = response.data.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g , "");
console.log(JSON.parse(JSON.stringify(x)));

CodePudding user response:

Here is an HTML template for you that you can try and fiddle with in your Browser Developer Console. If you want you can also replace "console.log()" with "alert()"

<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);
</script>
  • Related