admin管理员组

文章数量:1410731

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",

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",
Share Improve this question edited Feb 28, 2012 at 22:44 Bakudan 19.5k9 gold badges55 silver badges75 bronze badges asked Feb 28, 2012 at 22:42 user759235user759235 2,2073 gold badges42 silver badges85 bronze badges 5
  • possible duplicate of Safely turning a JSON string into an object – James Montagne Commented Feb 28, 2012 at 22:45
  • 2 So you have a string like '"color":"#000000", "font":"12px", "background":"#ffffff",'? – biziclop Commented Feb 28, 2012 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 Commented Feb 28, 2012 at 22:51
  • Please show the code you've tried already. – nnnnnn Commented Feb 28, 2012 at 22:58
  • See below for the solution. :) – user759235 Commented Feb 28, 2012 at 23:02
Add a ment  | 

2 Answers 2

Reset to default 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 ma, 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];
}

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);

本文标签: javascriptHow to loop a string as key value pairsStack Overflow