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:
- JSON.stringify then JSON.parse
- JSON.parse
- eval
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);
}
objectString.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": ');
objString
is generated?JSON.parse('{ "one": [1, 2, 3], "num": 1 }')
works with quotes around the keys. If not, you may need to look at sanitizing your JSON. stackoverflow.com/questions/9637517/…