0

How can I convert the following string using JavaScript to array:

from: var x = "{id:'2'},{name:'code,Barer'}";
to: var x1 = [{id:"2"},{name:"code,Barer"}];
codeBarer
  • 2,238
  • 7
  • 44
  • 75
  • 3
    Change the string so that it's valid JSON, then call `JSON.parse()`. – SLaks Nov 06 '13 at 20:24
  • That is not valid JSON as it requires double quotes and the properties' names to be quoted also. Also, you'd require to enclose that in `[]`s, such as: `var x = '[{"id":"2"},{"name":"code,Barer"}]';` – acdcjunior Nov 06 '13 at 20:26

2 Answers2

2

If you want that exact string to be an array object you can do this:

var x = "{id:'2'},{name:'code,Barer'}";
var newArray = eval("[" + x + "]");

Here are some the dangers of eval: Why is using the JavaScript eval function a bad idea?

How are you getting the variable x? If you can get whatever it is to spit out valid JSON (using JSON.stringify or something similar) you can then parse it correctly into JS (although some implementations of JSON parsers do use eval).

Community
  • 1
  • 1
Mingle
  • 846
  • 6
  • 13
  • +1 for mentioning `eval` with immediate warning on why not to use it – Ingo Bürk Nov 06 '13 at 20:28
  • Thanks! it worked well. I'm getting my x variable through another function/method created by someone else. The function gets data from REST and renders it into somewhat of a JSON format I guess. – codeBarer Nov 06 '13 at 22:55
  • I fully recommend modifying that other function that is created by someone else so that you don't put yourself at risk with the `eval` :P – Mingle Nov 06 '13 at 23:01
0

If you want to avoid using eval for security reasons try this

var string = "{id:'2'},{name:'code,Barer'}",
    array = string.substr(1, string.length - 2)
                  .split("},{")
                  .map(function(item){
                         item = item.split(":");
                         var result = {}, 
                             name = item[0], 
                             value = item[1].replace(/'/g, "");
                         result[name] = value;
                         return result
                       });
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98