Mohamed Hussain
Mohamed Hussain

Reputation: 7703

Not able to Parse HTML data attribute value as Javascript Object

I have the JS and HTML Code as below

var a=$("li").data("item");
console.log($("li").data("item").type);
  <li  data-item="{&quot;contentId&quot; : 5,&quot;type&quot; : &quot;PROGRAM&quot;, section_type:  &quot;PROGRAM_SECTION&quot;, &quot;active&quot;:&quot;false&quot;  }">data</li>

Trying to get the JS Object's type property value in the data-item attribute using the code

var a=$("li").data("item");
console.log($("li").data("item").type);

But I got var a=$("li").data("item"); as string, even JSON.parse(a) also not working see the screenshot enter image description hereand codepen http://codepen.io/shmdhussain/pen/VvXKLr

Please help me in parse the data. Thanks in advance for any help.

Upvotes: 1

Views: 842

Answers (3)

An0nC0d3r
An0nC0d3r

Reputation: 1303

Theres a few issues... try using the below HTML and JS instead.

HTML

<li data-item="{&quot;contentId&quot; : 5,
&quot;type&quot; : &quot;PROGRAM&quot;,
&quot;section_type&quot;:  &quot;PROGRAM_SECTION&quot;, 
&quot;active&quot; :&quot;false&quot;} ">data</li>

JS

var item = $("li").data("item");
var json = JSON.parse(item);    
$("li").text(json.type);

Upvotes: 1

vbranden
vbranden

Reputation: 5986

the problem is that your data is using &quot; when it should be using " so you need to replace &quot; with "

use this

JSON.parse($("li").data("item").replace(/&quot;/g,'"')).type;

assuming $("li").data("item") yields the data you wish to parse.

Upvotes: 1

Blue
Blue

Reputation: 22911

OK, so I found a few things wrong:

1: It should be

$("li").data("sna-item");

Also, you have an error in your data-sna-item (It's not valid json). There are no quotes around section_type

Here's an updated codepen: http://codepen.io/anon/pen/gaewrd

Upvotes: 1

Related Questions