简体   繁体   English

SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束

[英]SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

Okay so I'm trying to pull data from a json file that holds the status of a few LEDs, etc. I have a script that runs a few times a second and pulls the data and the webpage loads it.好的,所以我正在尝试从一个包含几个 LED 等状态的 json 文件中提取数据。我有一个每秒运行几次的脚本,它会提取数据并让网页加载它。 The problem is, after about 20+ times of the server reading the json file, eventually it will throw this error.问题是,服务器读取 json 文件大约 20 次后,最终会抛出这个错误。

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束

// For toggling the LED/switch status indicators using the json data
$(document).ready(function() {
    (function worker() {
        $.ajax({
            url: 'server_info.json',
            success: function(data) {
                var json = $.parseJSON(data);
                console.log(json); 
                if (json.led_1 == "off") {
                    // do stuff
                }        
                if (json.led_2 == "off") {
                    // do stuff
                } 
                if (json.led_3 == "off") {
                    // do stuff
                }        
            },
            complete: function() {
                // Schedule the next request when the current one's complete
                setTimeout(worker, 250);
            }
        });
    })();
});

The json file looks like this: json 文件如下所示:

{ "led_1": "on", "led_2": "on", "led_3": "on" } 

It seems to me that the json data is always properly formatted.在我看来,json 数据的格式总是正确的。 I'm not understanding where the error is coming from.我不明白错误来自哪里。 Any ideas?有任何想法吗?

Using Firefox debugging, I was able to see that the value type coming back was undefined when I would get that error.使用 Firefox 调试,当我收到该错误时,我能够看到返回的值类型是未定义的。 Doing a check for a null/undefined on the value to be parsed first, then if condition is false, proceed with parse, else handle condition resolved my issue.首先检查要解析的值是否为空/未定义,然后如果条件为假,则继续解析,否则处理条件解决了我的问题。

Use the "dataType" setting to identify the type of response so the .ajax() call knows its JSON and doesn't need to guess.使用“dataType”设置来识别响应的类型,这样 .ajax() 调用就知道它的 JSON 并且不需要猜测。

This may not solve the issue as it is likely your response is not returning JSON for the call that is throwing the error.这可能无法解决问题,因为您的响应可能没有为引发错误的调用返回 JSON。 If you add the error setting, you can see what the server is returning on error but if the requests completes, check the console for what is coming back from the server.如果添加错误设置,您可以看到服务器在错误时返回的内容,但如果请求完成,请检查控制台以了解从服务器返回的内容。 As I said, its likely not JSON if you are getting that error from $.parseJSON() to begin with.正如我所说,如果您从 $.parseJSON() 开始收到该错误,它可能不是 JSON。

$(document).ready(function() {
    (function worker() {
        $.ajax({
            url: 'server_info.json',
            dataType: 'json',
            success: function(data) {
                console.log(data); 
                if (data.led_1 == "off") {
                    // do stuff
                }        
                if (data.led_2 == "off") {
                    // do stuff
                } 
                if (data.led_3 == "off") {
                    // do stuff
                }        
            },
            error: function( data, status, error ) { 
                console.log(data);
                console.log(status);
                console.log(error);
            },
            complete: function() {
                // Schedule the next request when the current one's complete
                setTimeout(worker, 250);
            }
        });
    })();
});

Turns out, the error is nothing to do with JSON.事实证明,该错误与 JSON 无关。 It's actually because of the backend returning either a none JSON or empty string.这实际上是因为后端返回非 JSON 或空字符串。

// Update
    if(updateFile($id,$author)) {
      echo json_encode(
        array('message' => 'Post Updated')
      );
    } else {
      echo json_encode(
        array('message' => 'Post Not Updated')
      );
    }

As for me, this worked.至于我,这行得通。 Goodluck祝你好运

A list of reasons to get this error出现此错误的原因列表

There are more reasons for sure to get:肯定有更多的理由:

Uncaught SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data未捕获的 SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束

Even if the reasons may not have your use case in the end, the list should give some hints to those with this error.即使原因最终可能没有您的用例,该列表也应该为出现此错误的人提供一些提示。

Empty response since all params are undefined空响应,因为所有参数都未定义

Taking up the upvoted answer of using FireFox debugging , here is an example of how to use the debugger ( Ctrl+Shift+C or F12 --> Debugger).接受使用 FireFox 调试的赞成答案,这里有一个如何使用调试器的示例( Ctrl+Shift+CF12 --> 调试器)。 I have the same error message but not the same code.我有相同的错误消息,但代码不同。

  1. You need to check the checkboxes "Pause on exceptions" (I also checked "Pause on caught exceptions", I do not know whether that is needed) and您需要检查复选框“暂停异常”(我还检查了“暂停捕获异常”,我不知道是否需要)和

  2. trigger what you want to test.触发您要测试的内容。

在此处输入图像描述

  1. The error错误

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束

is thrown when the code reaches当代码到达时抛出

if (JSON.parse(resp) > 0){
  1. And it turns out that in my case, resp is an empty string (which cannot be parsed since it is empty).事实证明,在我的情况下, resp是一个空字符串(因为它是空的,所以无法解析)。

在此处输入图像描述

  1. As soon as you have found the line of the error, you can uncheck the checkbox "Pause on exceptions" and press "Resume" to get to the end of the code run.找到错误行后,您可以取消选中“异常暂停”复选框,然后按“恢复”以结束代码运行。

在此处输入图像描述

  1. Adding in front of the line above:在上面的行前面添加:

     if (resp != ""){...

seems to fix it, it runs through without errors, but that is not the solution since it only skips the step, but the update will not be done anymore.似乎可以修复它,它运行没有错误,但这不是解决方案,因为它只是跳过了这一步,但更新将不再完成。 I changed back to the code without if (resp != ""){ .我改回没有if (resp != ""){的代码。

  1. Checking the back-end (php) and frontend (js)检查后端(php)和前端(js)

You can use echo($sql);您可以使用echo($sql); to print the SQL in the Response of the Network tab:在网络选项卡的响应中打印 SQL:

在此处输入图像描述

The ajax back-end showed why the response was empty: a null value was passed, leading to a SQL like ajax 后端显示了响应为空的原因:传递了一个空值,导致类似 SQL

update my_table set where x = 123

though it should be虽然应该是

update my_table set my_var = 1 where x = 123

I solved this by changing the variables in javascript (js)我通过更改 javascript (js) 中的变量解决了这个问题

from

var my_var1 = row["my_var1"];

to

var my_var1 = row["my_var1"] ?? '';

and in php并在 php

from

$raw_my_var1 = $_REQUEST['my_var1'] ;
$my_var1 = $raw_my_var1 != NULL ? $raw_my_var1 : '' ;

or in one line:或在一行中:

$my_var1 = isset($_REQUEST['my_var1']) ? $_REQUEST['my_var1'] : '';

so that null values become empty strings.使空值成为空字符串。

In addition, you should also check (!):此外,您还应该检查(!):

empty($my_var1)

since an empty variable (if you want to write an empty string "" to a field in SQL) has still an isset($my_var1) = 1!因为一个空变量(如果你想写一个空字符串""到 SQL 中的一个字段)仍然有isset($my_var1) = 1!

These checks are likely what was meant by the answer with the most votes at the time of writing .这些检查很可能是撰写本文时得票最多的答案的意思。

This is only one step of the solution.这只是解决方案的一步。 It helps to pass a loop step in which some of the fields in the front-end are not filled.它有助于通过一个循环步骤,其中前端的某些字段未填充。

No permissions没有权限

You do not use SQL in your question, this is just to remind everyone of the permissions.您在问题中没有使用 SQL,这只是为了提醒大家权限。

When you use SQL in the back-end and your user does not have the read/write rights/permissions to select, insert, update, delete or whatever is used in your code in a sql back-end, you get the error in question as well.当您在后端使用 SQL 并且您的用户没有读/写权限/权限来选择、插入、更新、删除或在 sql 后端的代码中使用的任何内容时,您会收到相关错误也是。

If you want to update, this is not enough:如果要更新,这还不够:

在此处输入图像描述

An update will not work, and the response can become empty.更新将不起作用,并且响应可能变为空。 Have a look at your back-end code.看看你的后端代码。

Data type 'decimal' needed without string quotes in SQL SQL 中需要没有字符串引号的数据类型“十进制”

The error in question can also be thrown when the data type becomes a string of a numeric value in SQL, although the needed value is numeric.当数据类型变为 SQL 中的数值字符串时,也可能会引发有问题的错误,尽管所需的值是数值。

在此处输入图像描述

That is at least what I thought at first, it turned out that SQL can read a '1' as an integer 1 while it cannot read a '1.00' as a decimal 1.00 .这至少是我一开始的想法,事实证明 SQL 可以将'1'读取为整数1而它不能将'1.00'读取为十进制1.00 That is why it worked only when overwriting the 1.00 with a 1 in the front-end field.这就是为什么它只在前端字段中用1覆盖1.00时起作用。

The real reason was in the SQL of the back-end.真正的原因在于后端的 SQL。

To keep the passed value as a decimal or integer, I just removed the quotes that were (wrongly) added in the back-end SQL code.为了将传递的值保留为小数或整数,我只是删除了后端 SQL 代码中(错误地)添加的引号。

           $sql = $sql . "my_var_numeric='" . $value_numeric . "'";

to

           $sql = $sql . "my_var_numeric=" . $value_numeric ;

So that the field data type in the back-end, decimal(12,2), was passed.这样后端的字段数据类型decimal(12,2)就被传递了。

在此处输入图像描述

During my tests, I did not change this 1.00 field, but only the two text fields, therefore it was astonishing that another field that I had never changed would be the problem.在我的测试中,我没有更改这个1.00字段,而只更改了两个文本字段,因此令人惊讶的是,另一个我从未更改过的字段会成为问题。

Forgotten debug echo in the back end response后端响应中忘记调试回显

For debugging, I had a few echo($sql) in the ajax php back end that were added before the expected echo($result) = 1 of the sql query.为了调试,我在 ajax php 后端添加了一些echo($sql) ,它们是在 sql 查询的预期 echo($result) = 1 之前添加的。

Commenting the echo commands out again dropped the error in question as well.再次评论 echo 命令也删除了有问题的错误。

In another case, the unplanned echo also changed the error message slightly to在另一种情况下,计划外的回声也将错误消息稍微更改为

Uncaught SyntaxError: JSON.parse: unexpected end of data at line 1 column 3 of the JSON data未捕获的语法错误:JSON.parse:JSON 数据的第 1 行第 3 列的数据意外结束

(column 3 instead of column 1) (第 3 列而不是第 1 列)

Wrong variable name in the back end后端变量名错误

I also checked a variable for not to be empty although that variable did not exist, it had an unneeded prefix in my case, something like:我还检查了一个变量是否为空,尽管该变量不存在,但在我的情况下它有一个不需要的前缀,例如:

if ($not_existing_prefix_var1 != '' || $var2){
[... run sql]

which also threw the error in question.这也引发了有问题的错误。

I just had to change the code to我只需要将代码更改为

if ($var1 != '' || $var2){
[... run sql]

NULL inserted in NOT NULL field在 NOT NULL 字段中插入 NULL

I got the error我得到了错误

Uncaught SyntaxError: JSON.parse: unexpected end of data at line 1 column 3 of the JSON data未捕获的语法错误:JSON.parse:JSON 数据的第 1 行第 3 列的数据意外结束

(now column 3 instead of column 1) (现在是第 3 列而不是第 1 列)

when I tried to update a field in SQL with a NULL value when NULL was not allowed.当我尝试在不允许使用 NULL 时使用 NULL 值更新 SQL 中的字段时。

What is it all about这是什么一回事呢

In your case, it might be that in the back-end file, in a few cases only, the "on" and "off" field is an integer instead, misspelled like 'offf', has a forbidden special character in it, or even more likely, is null / not filled / undefined.在您的情况下,可能是在后端文件中,仅在少数情况下,“on”和“off”字段是一个整数,拼写错误,如“offf”,其中包含禁止的特殊字符,或者更有可能的是,为空/未填充/未定义。 An item that has other undefined values or is not in the right format.具有其他未定义值或格式不正确的项目。 Or there is a decimal data type in the data where an integer is in the source.或者数据中有一个十进制数据类型,其中一个整数在源中。 And so on.等等。 Or you have trailing commas or leading zeros.或者你有尾随逗号或前导零。 There is a wide range of such data type errors at SyntaxError: JSON.parse: bad parsing . SyntaxError: JSON.parse: bad parsing中存在大量此类数据类型错误。 The link is the official help for your error, shown in the debugger of the browser.该链接是您的错误的官方帮助,显示在浏览器的调试器中。

There might also be a wrong syntax of some item in the back-end file which might return a null response if you return a response only when the reading works.后端文件中的某些项目也可能存在错误的语法,如果您仅在读取工作时返回响应,则可能会返回空响​​应。 But that depends on your code then, since a syntax error in json would make the file unreadable.但这取决于您的代码,因为 json 中的语法错误会使文件不可读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符吗? - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data? 语法错误json.parse json数据第1行第1列的意外字符 - syntaxerror json.parse unexpected character at line 1 column 1 of the json data 语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据第3行第1列的意外字符 - SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据的第1行第2列出现意外字符 - SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data React SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的数据意外结束 - React SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的数据意外结束 OK - SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data OK Javascript 错误:SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的数据意外结束 - Javascript error: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data 调用其余的WS并获取:SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束 - Call a rest WS and get: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束[了解更多] - SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data[Learn More]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM