4

I get an error when trying to parse JSON from a HTML data attribute. This is the div I want to parse JSON from:

echo '<div class="udropdown" data-elements=\'{"option1" : "1", "option2" : "2" }\'></div>';

and this is the jQuery part (it's on click, so $(this) is necessary)

var ele = jQuery.parseJSON($(this).data('elements'));

but I keep getting this error:

Uncaught SyntaxError: Unexpected token o

5
  • shouldn't need to use parseJSON() since data() will do the parsing internally Commented Nov 8, 2015 at 12:42
  • But either way, if you are returning HTML, why not return the options already? What's the point of having a data attribute with JSON in it? Commented Nov 8, 2015 at 12:43
  • @AndréSilva lots of possible use cases, for example initialize a plugin Commented Nov 8, 2015 at 12:46
  • @charlietfl This seems not to be the case. Commented Nov 8, 2015 at 12:47
  • Please provide all relevant code context. Commented Nov 8, 2015 at 12:48

3 Answers 3

3

From the documentation for jQuery.data:

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.

$(this).data('elements') will have parsed the JSON in the string to an object already.

jQuery.parseJSON(object) is equivalent to jQuery.parseJSON(object.toString()) which gives you jQuery.parseJSON("[object Object").

Just skip the manual parseJSON step. jQuery has already done it for you.

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

Comments

1

Most likely you already have a parsed object there. In this case parseJSON tries to treat your input as a string and as long as it is already an object it will be treated as the following string:

[object Object]

or similar. It thinks then that symbol [ is a beginning of some array (which is still a valid JSON) and o is exactly what it does not expect to get there because it either must be a number, boolean, or one of those symbols ', " or {.

Just check the data type of $(this).data('elements') - it must be an object.

Try the following:

JSON.parse({})

that will return exactly the same error.

Comments

1

$(this).data('elements') return an object so you don't have to parse anything just use the ele returned, e.g :

$('.udropdown').click(function(){
    var ele = $(this).data('elements');
    console.log(ele.option1, ele.option2);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="udropdown" data-elements='{"option1" : "1", "option2" : "2" }'>Click HERE</div>

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.