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
2 Answers
Reset to default 8If 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
版权声明:本文标题:javascript - How to loop a string as key value pairs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745036504a2638818.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论