开发者

need help on getting a value from "{"k1":"v1", "k2":"v2"}"

开发者 https://www.devze.com 2023-04-12 03:45 出处:网络
i got a result from someone else code elem.getAttribute(\"additional-attributes\") ...the result is like:

i got a result from someone else code

elem.getAttribute("additional-attributes")

...the result is like:

"{"k1":"v1", "k2":"v2"}"

so do I have to parse the str开发者_运维技巧ing to get "v2" from "k2"? or are there better ways to get the value?

Thanks!


OK, so you want to use JSON.parse to get the object, and then obj.k1 or obj.k2 to get the values...


You could just split on comma then colon. Or a simple regex could do the trick.


If the string is like this actually (note the ' as a string operator):

var string = '{"k1":"v1", "k2":"v2"}'

You can do this (to convert that string into JS object):

var obj = eval("("+string+")");

And then to access k2 value do this:

var k2value = obj.k2;

If the string is badly formated, you can reformat it so it is valid JS string, and then do the eval() on it to make it an object.

0

精彩评论

暂无评论...
验证码 换一张
取 消