7

Here's my HTML:

<input type="text" data-setup='{ "method" : "checkbox" }'>

Here's my JavaScript so far:

var a = document.querySelectorAll('[data-setup]')
for (var i=0;i<a.length;i++) {
    alert(a[i].getAttribute('data-setup'));
}

This then alerts:

ALERT: { "method" : "checkbox" }

But how can I access the JSON "method"? I want to essentially be able to alert the word "checkbox". Any help appreciated.

3
  • data-passwrd or data-setup? Commented Jun 25, 2013 at 15:24
  • setup, sorry markup glitch. Refresh! Commented Jun 25, 2013 at 15:25
  • If you're using jQuery, you can just say var a = $('#mySelector').data('setup'); Commented Apr 5, 2014 at 15:50

2 Answers 2

7

JSON.parse would be the simplest way to create a proper object from that JSON:

for (var i=0;i<a.length;i++) {
    var obj = JSON.parse(a[i].getAttribute('data-psswrd'));
    alert(obj.method); //will alert what was in the method property
    console.log(obj); // should log a proper object
}

Of course this won't work in older browsers, so you'll need to shim it if you want that kind of browser support. Douglas Crockford has a shim here, and or course jQuery has a JSON parsing method if you were already using that utility.

Sign up to request clarification or add additional context in comments.

3 Comments

Do you know what browsers this would work in? IE8 by any chance? :)
@Halcyon21 - had to look it up - yeah - looks like this is something IE8 actually does support blogs.msdn.com/b/ie/archive/2008/09/10/native-json-in-ie8.aspx
That's interesting, was more a hopeful question rather than expecting a 'yes' - but that's really good. IE8 has some blessings at least... Thanks for the help, will mark this as chosen.
3

You need to use JSON.parse method for this:

var myJSON = JSON.parse( a[i].getAttribute('data-psswrd') );
alert( myJSON );

This is supported in all modern browsers and in IE8+.

If you need to support older browsers here is little hack. See Browser compatibility section.

1 Comment

yes, now you can use it like Object: alert( myJSON.method ); developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.