Skip to content

Can’t parse JSON to Javascript object

I have this HTML box:

<span>Select depatament</span><span>
    <select id="department" onchange="EnableSlaveSelectBox(this)" data-slaveelaments='{"a": 1, "b": "2"}'>
       <option selected disabled>-Select-</option>
    </select>
</span>

Event onchange() implementation:

function EnableSlaveSelectBox(element) {
    var d = $('#department').data('slaveelaments');
    alert($.parseJSON(d));
}

But when onchange() event is fired I get on this row:

alert($.parseJSON(d));

This error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

return JSON.parse( data + “” );

Any idea why I get error above?

Answer

In your case you don’t need use parseJSON, because d is Object,

function EnableSlaveSelectBox(element) {
    var d = $('#department').data('slaveelaments');

    console.log(d.a);
    console.log(d.b);
}

Example

When the data attribute is an object (starts with ‘{‘) or array (starts with ‘[‘) then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn’t parseable as a JavaScript value, it is left as a string.

$.data