In my html I've got a table:
<table id="table" data-keys="{{keys}}">
where keys are an array (I later succesfully call
{% for k in keys %}).
But when in my js I call:
$("#table").data("keys") the result is string:
"['', 'Value1', 'Value2', 'Value3']"
Is there anything smart that I can do to actually get the table or do I simply need to parse the string and convert it by myself?
You have to use double quotes for the string to be valid JSON. It will then be automatically parsed by jQuery.
const a = $('#a').data("keys");
const b = $('#b').data("keys");
console.log(typeof a, a)
console.log(typeof b, b)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a" data-keys='["", "a", "b", "c"]'></div>
<div id="b" data-keys="['', 'a', 'b', 'c']"></div>
Every attempt is made to convert the attribute's string value to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) [...] When a string starts with '{' or '[', then jQuery.parseJSON is used to parse it; it must follow valid JSON syntax including quoted property names. A string not parseable as a JavaScript value is not converted.