简体   繁体   中英

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. The problem is, after about 20+ times of the server reading the json file, eventually it will throw this error.

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

// 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:

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

It seems to me that the json data is always properly formatted. 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. 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.

This may not solve the issue as it is likely your response is not returning JSON for the call that is throwing the error. 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.

$(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. It's actually because of the backend returning either a none JSON or empty string.

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

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). 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

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).

在此处输入图像描述

  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 != ""){ .

  1. Checking the back-end (php) and frontend (js)

You can use echo($sql); to print the SQL in the Response of the Network tab:

在此处输入图像描述

The ajax back-end showed why the response was empty: a null value was passed, leading to a SQL like

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)

from

var my_var1 = row["my_var1"];

to

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

and in 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!

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.

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.

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

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.

在此处输入图像描述

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 . That is why it worked only when overwriting the 1.00 with a 1 in the front-end field.

The real reason was in the SQL of the back-end.

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 . "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.

在此处输入图像描述

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.

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.

Commenting the echo commands out again dropped the error in question as well.

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

(column 3 instead of column 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

I got the error

Uncaught SyntaxError: JSON.parse: unexpected end of data at line 1 column 3 of the JSON data

(now column 3 instead of column 1)

when I tried to update a field in SQL with a NULL value when NULL was not allowed.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM