4

I want to loop a string as a key/value pairs. The data is given me as a string(i am using the jstorage plugin).

I have tried to split the string as an array, but it is not returning the right key/values.

Example

 "color":"#000000", "font":"12px", "background":"#ffffff",
Bakudan
  • 19,134
  • 9
  • 53
  • 73
user759235
  • 2,147
  • 3
  • 39
  • 77
  • possible duplicate of [Safely turning a JSON string into an object](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – James Montagne Feb 28 '12 at 22:45
  • 2
    So you have a string like `'"color":"#000000", "font":"12px", "background":"#ffffff",'`? – biziclop Feb 28 '12 at 22:45
  • 1
    jStorage lets you store arbitrary objects as values, so you shouldn't be in this position to begin with. You should change your sentence "The data is given me as a string" to "____ gives me the data as a string", and then fix whatever ____ is! – ruakh Feb 28 '12 at 22:51
  • Please show the code you've tried already. – nnnnnn Feb 28 '12 at 22:58
  • See below for the solution. :) – user759235 Feb 28 '12 at 23:02

2 Answers2

8

If you always get the string like that, i.e. keys and values in double quotes, you can add {...} to the string and parse it as JSON:

// remove trailing comma, it's not valid JSON
var obj = JSON.parse('{' + str.replace(/,\s*$/, '') + '}');

If not, splitting the string is easy as well, assuming that , and : cannot occur in keys or values:

var obj = {},
    parts = str.replace(/^\s+|,\s*$/g, '').split(',');

for(var i = 0, len = parts.length; i < len; i++) {
    var match = parts[i].match(/^\s*"?([^":]*)"?\s*:\s*"?([^"]*)\s*$/);
    obj[match[1]] = match[2];
}
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You need to evaluate it into a JavaScript object. Provided you trust the source, or can validate the content, you can do this:

s = document.createElement('script')
s.type='text/javascript';
s.innerHTML = 'var data = {'+ text + '}';
document.getElementsByTagName('head')[0].appendChild(s);
Terence Johnson
  • 1,637
  • 1
  • 16
  • 21