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",
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With