最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught SyntaxError: Unexpected end of JSON input [} - Stack Overflow

programmeradmin3浏览0评论

Uncaught Syntax Error: Unexpected end of JSON input

help why I am getting such error

 $('.view-profile').on('click', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var str = $(this).data('citizens');
    var citizensArray = JSON.parse(str);
    alert(citizensArray[0].id);
});

html & php

     <button type="button" class="btn btn-success btn-sm view-profile" data- 
     citizens="<?php echo json_encode($citizens);?>" data-id="<?php echo 
     $citizen['id'];?>"><i class="fa fa-fw fa-user-o"></i> Profile</button> 

Uncaught Syntax Error: Unexpected end of JSON input

help why I am getting such error

 $('.view-profile').on('click', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var str = $(this).data('citizens');
    var citizensArray = JSON.parse(str);
    alert(citizensArray[0].id);
});

html & php

     <button type="button" class="btn btn-success btn-sm view-profile" data- 
     citizens="<?php echo json_encode($citizens);?>" data-id="<?php echo 
     $citizen['id'];?>"><i class="fa fa-fw fa-user-o"></i> Profile</button> 
Share Improve this question edited Mar 19, 2018 at 7:43 Satpal 133k13 gold badges167 silver badges170 bronze badges asked Mar 19, 2018 at 7:35 Karl JucutanKarl Jucutan 991 gold badge1 silver badge9 bronze badges 2
  • can you copy the value of str ? – ben Commented Mar 19, 2018 at 7:37
  • JSON in str in not in correct format, copy it's value to some online JSON parser to find error. – Rehan Haider Commented Mar 19, 2018 at 7:39
Add a ment  | 

2 Answers 2

Reset to default 4

Wrap the data-citizens in single quotes i.e. data-citizen='<?php echo json_encode($citizens);?>' as existence of " is JSON string will abruptly terminate the attribute value.

And, You don't need to use JSON.parse() with .data(), if the data is valid JSON format the method will return JavaScript object.

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.

Using JSON.parse() with valid JSON result if above error.

So just use

var citizensArray = str;

$('.view-profile').on('click', function(e) {
  e.preventDefault();
  var str = $(this).data('citizens');
  console.log(str);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-success btn-sm view-profile" data-citizens='{ "id" : 1}'> Profile</button>

Before you add JSON into HTML attribute, make sure you encode it.

data-citizens="<?php echo htmlspecialchars(json_encode($citizens));?>"
发布评论

评论列表(0)

  1. 暂无评论