5

I'm sure this is answered somewhere, but it is my lack of terminology knowledge that can't find where to look.

I am dynamically creating some Html as a result of some json data loaded from the server.

I am using createElement, and setAttribute to create the html and append it to the main body.

However, my dynamic html contains a "data-" attribute, which has further nested properties. An example end goal is such:

<li>
   <span class=item data-item='{"width": 100, "height": 100, 
    "properties": { "Name": "foo", "Surname": "bar" }}'></span>
</li>

I have had some success when running:

li.setAttribute("data-item", '{"width": 100, "height": 100, "properties": 
                 { "Name": "foo", "Surname": "bar" }}');

But then when I come to use the data item elsewhere in my java-script, the attributes are recognized as a string as opposed to an object. When I hard code the HTML, the data-item is loaded correctly as an object. I have made the assumption it must be because I am incorrectly setting this attribute.

Stinkidog
  • 425
  • 2
  • 7
  • 19
  • How do you access the attribute? Are you sure you get an object when reading it from hard-coded HTML? Afaik, HTML attributes are **always** strings – Lennholm Aug 08 '17 at 11:21
  • If you access the data attribute using jQuery's `data()` method, it will deserialise the JSON for you. Otherwise you'll need to do it manually, as the two answers below show. – Rory McCrossan Aug 08 '17 at 11:24
  • @RoryMcCrossan I think the OP is using Vanilla JS not JQyery. but I agree with your views. – Shakti Phartiyal Aug 08 '17 at 11:25
  • 1
    @ShaktiPhartiyal their example is, however they tagged the question with jQuery, so thought I'd offer the alernative – Rory McCrossan Aug 08 '17 at 11:27
  • I managed to solve my problem by the suggested answers. When using JSON.parse(), I had an error that my string was not in JSON format, turns out I was missing a closing brace. Always the simple things... – Stinkidog Aug 08 '17 at 11:38

2 Answers2

2

You are getting a string because the property is set as a string, you can get the data as an object after parsing it like so:

var li = document.createElement('li');
li.id = "li1";
li.setAttribute("data-item", '{"width": 100, "height": 100, "properties": { "Name": "foo", "Surname": "bar" }}');
li.innerHTML = "SAMPLE li";
document.body.appendChild(li);


var data = document.getElementById('li1').getAttribute('data-item');
data = JSON.parse(data);
console.log(data);
Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
1

You can use JSON.parse to turn it into an object :

var result = JSON.parse('{"width": 100, "height": 100, "properties": { "Name": "foo", "Surname": "bar" }}');
// result.width => 100
// result.properties.Name => "foo"     etc...
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55