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
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.
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.
$(this).data('elements')
return an object so you don't have to parse anything just use the ele
returned, eg :
$('.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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.