Reputation: 7703
I have the JS and HTML Code as below
var a=$("li").data("item");
console.log($("li").data("item").type);
<li data-item="{"contentId" : 5,"type" : "PROGRAM", section_type: "PROGRAM_SECTION", "active":"false" }">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 and codepen http://codepen.io/shmdhussain/pen/VvXKLr
Please help me in parse the data. Thanks in advance for any help.
Upvotes: 1
Views: 842
Reputation: 1303
Theres a few issues... try using the below HTML and JS instead.
HTML
<li data-item="{"contentId" : 5,
"type" : "PROGRAM",
"section_type": "PROGRAM_SECTION",
"active" :"false"} ">data</li>
JS
var item = $("li").data("item");
var json = JSON.parse(item);
$("li").text(json.type);
Upvotes: 1
Reputation: 5986
the problem is that your data is using "
when it should be using " so you need to replace "
with "
use this
JSON.parse($("li").data("item").replace(/"/g,'"')).type;
assuming $("li").data("item")
yields the data you wish to parse.
Upvotes: 1
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