-1

I have a string variable in javascript called temp:

temp = "[{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]"

How I can convert the string temp to array?

To be like:

temp = [{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]

2_slow
  • 49
  • 5
  • Why don't you fix whatever produces the first `temp` to instead produce valid JSON? – VLAZ Oct 12 '20 at 19:03

4 Answers4

4

If the string were in valid JSON format you could use JSON.parse(). But it's not, so the only general solution (short of writing your own parser) is eval().

var temp = "[{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]"
var result = eval(temp);
console.log(result);
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

This can be extracted as array using eval javascript function.

const input = "[{a: 1, b: 1}, {a: 2, b: 2}, {a: 3, b: 3}]";
const output = eval(input);
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
1
const arr = ['foo,', 'bar', 'red,', 'car']
console.log(arr.join(' '))//"foo, bar red, car"

You can simply use the join() function to convert the array into string

Force Bolt
  • 1,117
  • 9
  • 9
-1

JSON.parse should work, if I understand the question correctly

You can use the answer from this question for fixing the JSON before parsing it

adamski234
  • 89
  • 8