How to parse a NON JSON STRING to a Object in javascript

Viewed 739

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);
}
5 Answers

Wrap it in parentheses.

let objString = '{ one: [1, 2, 3], num: 1 }';
let obj = eval('(' + objString + ')');

Needless to say though, you should only ever eval things from trusted sources.

I've found a really cheeky way to do it

let obj = {}
eval("obj =" + '{ one: [1, 2, 3], num: 1 }')

Turn your String into this format below and it should parse properly using JSON.parse()

let objString = '{ "one": [1, 2, 3], "num": 1 }';

console.log(JSON.parse(objString));

Since using eval() is security risk. I would suggest you to try converting your string to a parsable JSON string then use JSON.parse() to parse.

const keyFinderRegEX = /([{,]\s*)(\S+)\s*(:)/mg;
const convertedJSONString = '{ one: [1, 2, 3], num: 1 }'.replace(keyFinderRegEX, '$1"$2"$3');
const parsedObj = JSON.parse(convertedJSONString);

    console.log(parsedObj)

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 + ";")();
Related