Reputation: 1438
I have to clean my data using few replaceAll
function.
JSON.parse(data.replaceAll('{\'', '{"').replaceAll('\'}', '"}').replaceAll('\',\'', '","').replaceAll('\': \'', '": "').replace(/[\n\r]+/g, ' ').replaceAll(" ", " "));
Is there a better way of doing this?
Any suggestions would be appreciated.
Thanks in advance
Upvotes: 0
Views: 91
Reputation: 1015
You could clean up the code and define your replacements in an array of pairs and iterate through it using reduce
const replacements = [["{'", '{"'], ["'}", '"}'], ["','", '","'], ["': '", '": "'], ['\n', ' '], ['\r', ' '], [' ', ' ']];
const data = `{' {'{'{' {' '}'} '}'} ','',' ',' ': ' ': '': '': ' Hello\n\r\n\n\r\n\n\r\nWorld\n\r`;
const newData = replacements.reduce((a, [token, replacement]) => a.replace(new RegExp(token, 'g'), replacement), data);
console.log(newData);
But as mentioned by Dean Taylor it's best to use a library to parse non-standard JSON data (if that is what you're trying to do).
Upvotes: 3