0

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?

3 Answers 3

3

Because, interestingly, jQuery seems to automatically parse the string to an object. To test this:

alert(d); // [object Object]

Or do this to see the stringified version again:

alert(JSON.stringify(d)); // {"a":1,"b":"2"}

Aside: I didn't know jQuery did that until I tested it.

Sign up to request clarification or add additional context in comments.

1 Comment

I was just about to post the same thing . . . you learn something new every day. :) Nice feature jQuery guys!
2

jQuery data() will already convert properly formatted json to array or object.

This is as documented in APi

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() API DOCS

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.