javascript 未捕获的语法错误:JSON 输入 [} 意外结束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49357830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:32:52  来源:igfitidea点击:

Uncaught SyntaxError: Unexpected end of JSON input [}

javascriptphpjson

提问by Karl Jucutan

Uncaught Syntax Error: Unexpected end of JSON input

未捕获的语法错误:JSON 输入意外结束

enter image description here

在此处输入图片说明

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

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> 

回答by Satpal

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

包裹data-citizens在单引号,即data-citizen='<?php echo json_encode($citizens);?>'由于存在"是JSON字符串会突然终止的属性值。

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

而且,您不需要使用JSON.parse()with .data(),如果数据是有效的 JSON 格式,该方法将返回 JavaScript 对象。

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSONis 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.

当数据属性为对象(以'{'开头)或数组(以'['开头)时,则jQuery.parseJSON用于解析字符串;它必须遵循有效的 JSON 语法,包括带引号的属性名称。如果该值无法解析为 JavaScript 值,则将其保留为字符串。

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

JSON.parse()如果出现上述错误,则使用有效的 JSON 结果。

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.com/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>

回答by Thum Choon Tat

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

在将 JSON 添加到 HTML 属性之前,请确保对其进行编码。

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