Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop a string as key value pairs

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",
like image 615
user759235 Avatar asked Feb 22 '23 07:02

user759235


1 Answers

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];
}
like image 70
Felix Kling Avatar answered Feb 23 '23 20:02

Felix Kling