0

I have such attribute in my element:

data-variations="{"2005":"11.99","2006":"15.99","2007":"19.99"}"

Is there any way to convert it into an object, which can look like:

obj = {2005:11.99, 2006:15.99, 2007:19.99}

I've tried first to get this attribute as string and split it with "," for further manipulations, but realized that there must be better and cleaner solution

1
  • 1
    The data method automatically parses attribute values that contain JSON. The only thing you'd have to do is iterate over the object and convert the values to numbers (or of course simply store them as numbers in the first place). Commented Sep 25, 2015 at 16:13

2 Answers 2

3

This is a JSON string. You can use JSON.parse() to parse it as an object.

Actually, since you are using jQuery, it will do that for you if you use .data().

var obj = $(element).data('variations')
Sign up to request clarification or add additional context in comments.

Comments

-1

Try this:

var text = "{"2005":"11.99","2006":"15.99","2007":"19.99"}";

obj = JSON.parse(text);

$.each(obj, function(k, v) {

//use k as key and v as value

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.