1

Convert Array-String to Object with Javascript or jQuery

here is my array

data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]

expected output is object

data=[{X:7,Y:12.5},{X:8,Y:15},{X:9,Y:12.5}]

enter image description here

how to do that?

1
  • 3
    How do you end up with the objects in a stringified format? You would be better to change how you receive them instead of stringifying/parsing them. Commented Jan 7, 2016 at 8:45

4 Answers 4

1

You can try something like this:

var data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];

data = data.map(function(item){
  item = item.replace(/{/g, "{\"");
  item = item.replace(/}/g, "\"}");
  item = item.replace(/:/g, "\":\"");
  item = item.replace(/,/g, "\",\"");
  return JSON.parse(item);
})

console.log(data)

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is better :)
0

Try this:

data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.join(',');
data = data.replace(/X/g,'"X"');
data = data.replace(/Y/g,'"Y"');
data = JSON.parse("["+data+"]");

Just convert array to string and do clean up that can be parsed to json.

Comments

0

Simple solution is to replace the X and Y with "X" & "Y". In order to create a string key that can be parse as JSON.

data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]

for(var i in data){
    tmp = data[i].replace("X",'"X"').replace('Y','"Y"')
    data[i] = JSON.parse(tmp)
}

Enjoy.

Comments

0
var reg = /[^{,]+?(?=:)/g;
var data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
    return JSON.parse(item.replace(reg, "\"$&\""));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.