'How to get the json from a data attribute using only .attr() (or equivalent)

I feel like I am stuck on the most simple thing but I can't seem to figure out a way to solve my problem.

I have a json array that I'd like to pass to my javascript through a data attribute on a div like that:

<div id="scope" data-json='["apple","pear"]'></div>

My problem is that I can only get that value using anything BUT .data('json').

Here's a fiddle with what I'm looking for: https://jsfiddle.net/Wurielle/p17d71m0/1/

You can see in the console that logging with .data() returns a json array (which is exactly what I need) but logging with .attr() returns just plain text. Unfortunately I can NOT use .data() for multiple reasons.

I thought about using JSON.stringify and JSON.parse but I can't get a result identical to the .data() option.

Is there any way to get the json from a data attribute using anything but .data()?



Solution 1:[1]

Leaving jQuery out entirely, we get the same result as with .data():

const json    = document.getElementById('scope').dataset.json;
const decoded = JSON.parse(json);

console.log("JS-only:");
console.log(decoded);

console.log("jQuery:");
console.log($('#scope').data('json'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scope" data-json='["MIL","QPL"]'></div>

Solution 2:[2]

var article = document.getElementById('scope');
var dataset = article.dataset.json;
JSON.parse(dataset);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 David Aguirre