I am having trouble with parsing a non-json object string to an actual object in javascript
the example string looks like:
let objString = '{ one: [1, 2, 3], num: 1 }';
what I want it to look like is
obj = { one: [1, 2, 3], num: 1 };
So far I have tried:
None of these work for rather obvious reasons but I am stuck at how to accomplish this, this is for a class I am writing to run and evaluate code, below is a snippet of the method in question.
compare() {
const { testCaseInfo, stdout } = this;
const expected = testCaseInfo.expected;
if (this.err || stdout.length < 1) { return false };
let parsedAnswer = stdout;
parsedAnswer = parsedAnswer.split('\n').join('');
/* Need help here, some edge case of Obj strings */
if (parsedAnswer.indexOf('{')) {
}
// This works for everything else
parsedAnswer = JSON.parse(parsedAnswer);
this.output = parsedAnswer;
return _.isEqual(parsedAnswer, expected);
}
A bit late to the party but I've just run into this myself so I thought I would give it a quick search and this thread popped up. Anyway, I would rather use this:
let obj = new Function("return " + objString + ";")();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With