1

I'm having trouble with converting an HTML-data attribute to a Javascript Object.

Here is what I do:

The Attribute looks like:

<a id="stringObj" data-string="{'Foo':'Bar'}">Some A-Tag</a>

In Javascript / JQuery I do as followed:

var obj = $("#stringObj").data('string').replace(/'/g,"\"");
obj = JSON.stringify(obj);
obj = JSON.parse(obj);

I of just used the JSON.stringify method for clean results, but it doesn't really matter. I also tried "eval" on the result but it keeps beeing a "string" on console.log(typeof obj) test.

How do I get an object from the attribute so I could use it like alert(obj.Foo);?

1
  • Your quotes are wrong. Check out my answer. You have to have a valid JSON... Commented Jun 25, 2018 at 11:41

4 Answers 4

3

When you are using jQuery.data(), it will be returning it as an object by default, when you use valid JSON. If possible, please try to swap the " and '.

$(function() {
  var data = $("#stringObj").data("string");
  console.log(typeof data);
  console.log(data.Foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="stringObj" data-string='{"Foo": "Bar"}'>Some A-Tag</a>

If you can't change the HTML code for some reason (can't swap the ' and "), use the following snippet:

$(function() {
  var data = $("#stringObj").data("string").replace(/'/g, '"');
  data = JSON.parse(data);
  console.log(typeof data);
  console.log(data.Foo);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="stringObj" data-string="{'Foo': 'Bar'}">Some A-Tag</a>

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

Comments

2

You can do it this way: https://codepen.io/creativedev/pen/NzBvYZ

var obj = $("#stringObj").data('string').replace(/'/g,"\"");
obj = JSON.parse(obj);
alert(obj.Foo);

1 Comment

There's a better method... :) Swap the quotes... Look at my answer.
1

You can also do it without jQuery:

var stringAttr = document.getElementById("stringObj").dataset.string.replace(/'/g,"\"");
var myObj = JSON.parse(stringAttr);
console.log(myObj.Foo);

Comments

0

I just deleted the JSON.stringify and it worked for now. Of course I tested it a several times before with no success but it does work for some reason :D - thank you guys.

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.