user13291588
user13291588

Reputation:

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

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

Upvotes: 4

Views: 4097

Answers (6)

N. Kudryavtsev
N. Kudryavtsev

Reputation: 4071

In order to avoid using eval, you can check if your input strings always comply to JSON5 format. It is less strict than traditional JSON and allows, e. g., not using quotes for key names definition, like in ECMAScript objects.

In order to parse JSON5 strings, use JSON5 npm package. Its API is the same as in the standard JSON object: you can just import it, write JSON5.parse(objString) and that's it.

Upvotes: 1

Fygo
Fygo

Reputation: 4665

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

Upvotes: 4

Pushpendu Ghosh
Pushpendu Ghosh

Reputation: 27

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

Upvotes: -1

Ravikumar
Ravikumar

Reputation: 2205

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)

Upvotes: 1

Siguza
Siguza

Reputation: 23840

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.

Upvotes: 1

Ashley McVeigh
Ashley McVeigh

Reputation: 59

I've found a really cheeky way to do it

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

Upvotes: 1

Related Questions