0

I wanted to convert this string "{a:2, b:4}" into Object {a:2, b:4}.

I tried JSON.parse("{a:2, b:4}") and got no result.

The real data I'm getting is a little complex and can't post here because of company data.

Is there any way in JS to achieve it.

harish kumar
  • 1,732
  • 1
  • 10
  • 21
  • 2
    The reason JSON.parse didn't work is because that is not JSON. If your string was `{"a":2, "b":4}`, then you could have used JSON.parse – Alberto Rivera Jun 17 '20 at 17:21
  • 1
    Is there a way? Sure, you could always use `eval` (please don't tho). Otherwise you need to transform that into valid JSON somehow or parse it into an object manually. – CRice Jun 17 '20 at 17:22
  • 1
    Where does the data come from? Is it a user-provided object or is it something that you are building completely by yourself? – Sebastian Kaczmarek Jun 17 '20 at 17:24
  • Thanks @AlbertoRivera for comment.. will check – harish kumar Jun 17 '20 at 17:32

3 Answers3

2

let parsedObject = JSON.parse('{"a":2, "b":4}')
console.log(parsedObject)

JSON.parse('{"a":2, "b":4}') would work.

kooskoos
  • 4,622
  • 1
  • 12
  • 29
1

you may use eval function:

s = '{a:2, b:4}'
eval('('+s+')')
// returns {a:2, b:4}

Don't forget to put your object in (...)

Mahdi Jadaliha
  • 1,947
  • 1
  • 14
  • 22
0

You can't write a reliable parser unless you know the syntax of the format but, for the simple test case you've shared, you could do something like this (error checking omitted for brevity):

const input = '{a:2, b:4}';
const parsed = input.match(/^\{([a-z]+):(\d+),\s*([a-z]+):(\d+)\}$/);
const output = {
  [parsed[1]]: parsed[2],
  [parsed[3]]: parsed[4]
}
console.log(output, typeof output);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360