Ошибка parse error at line 1 column 1

I test my data using the latest version on my MacBook, everything is ok. I need more tests for my case. Thank you for you pay attention to this issue.

json json_obj = json::parse(R"(
{
    "Data/Images/AmberLogo.png": {
        "props": {
            "comression": "LowCompress",
            "usage": "sRGB",
            "mipmap": "Off",
            "premul": "Premul"
        },
        "prop_raw_info": "-s_-p_",
        "size": {
            "width": 1024,
            "height": 256,
            "raw_size": 9.291,
            "channels": [
                "L",
                "A"
            ],
            "comp_astc_size": 256.215,
            "comp_etc_size": 256.215
        }
    }
}
)");

for (auto it = json_obj.begin(); it != json_obj.end(); it++) {
	auto info_value = it.value();
	auto size_info = info_value.at("size").get<json>();
	
	std::cout << size_info["width"].get<int>() << std::endl;
	std::cout << size_info["height"].get<int>() << std::endl;
	
	// Print error info in this line, but now, everything is ok.
	auto channels = size_info["channels"].get<std::vector<std::string>>();
	for (auto &channel : channels) {
	  std::cout << channel << std::endl;
	}
}

tl;dr — save your project as .qgs, not .qgz

I’ve had a look at the code and seen a few things that might need looked at

In particular I see lots of references to ‘.qgs’ as the project filename extension. In 3.2.0 at least, the project file extension seems to be .qgz by default (at least for projects I’ve created in 3.2). I must have missed the memo on that :)

Because it assumes the file is .qgs, it can’t find the file, so the file is empty. An empty document is not valid XML, which is why it fails on line 1 column 1.

If you can find a way of changing this default to use the old .qgs format, that might be worth a try? (Don’t try to rename the file extension manually; I think qgz is a compressed format).

Have tried hacking my local copy of the plugin but to no avail :-(

EDIT have raised issue for you. This might not be the cause but it’s worth a try!

EDIT2 QConsolidate3 is actually a separate project. It’s logged as an issue already there

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.

enter image description here

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

enter image description here

  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.

enter image description here

  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:

enter image description here

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:

enter image description here

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.

enter image description here

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.

enter image description here

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.

When working with JSON data, it is common to encounter errors during parsing. One such error is the Unexpected end of JSON input at line 1 column 1 of the JSON data. In this guide, we will explore the cause of this error and provide a step-by-step solution to fix it.

Table of Contents

  • Understanding the Error
  • Step-by-Step Solution
  • FAQs
  • Related Links

Understanding the Error

The error message Unexpected end of JSON input at line 1 column 1 of the JSON data occurs when you attempt to parse an empty or invalid JSON string using the JSON.parse() method. This error is usually due to:

  1. An empty JSON string being passed to the JSON.parse() method.
  2. Incorrectly formatted JSON data, such as missing brackets, quotes, or commas.

Before diving into the solution, let’s understand the basics of the JSON.parse() method.

JSON.parse()

The JSON.parse() method is a built-in JavaScript function used to convert a JSON string into a JavaScript object. It takes a JSON string as its argument and returns a JavaScript object based on the structure of the JSON data.

const jsonString = '{"name": "John", "age": 30}';
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj); // { name: 'John', age: 30 }

Step-by-Step Solution

To fix the Unexpected end of JSON input at line 1 column 1 of the JSON data error, follow these steps:

Verify the JSON data: Ensure that the JSON string being parsed is not empty and is properly formatted. You can use an online JSON validator, such as JSONLint, to check the validity of your JSON data.

Check for empty JSON strings: Add a conditional statement to check for empty JSON strings before calling the JSON.parse() method. This will prevent the error from occurring when parsing an empty string.

const jsonString = '';

if (jsonString) {
  const jsonObj = JSON.parse(jsonString);
  console.log(jsonObj);
} else {
  console.warn('Empty JSON string. Skipping JSON.parse().');
}
  1. Handle parsing errors: Wrap the JSON.parse() method in a try-catch block to handle any errors that may occur during parsing. This is useful when dealing with dynamic JSON data, as it allows you to catch and handle errors gracefully.
const jsonString = '{"name": "John", "age": 30';

try {
  const jsonObj = JSON.parse(jsonString);
  console.log(jsonObj);
} catch (error) {
  console.error('Error parsing JSON:', error.message);
}

By following these steps, you should be able to resolve the Unexpected end of JSON input at line 1 column 1 of the JSON data error and handle any potential issues that may arise during JSON parsing.

FAQs

1. What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. Learn more about JSON on the official JSON website.

2. How do I stringify a JavaScript object to JSON?

To convert a JavaScript object into a JSON string, you can use the JSON.stringify() method. This method takes a JavaScript object as its argument and returns a JSON string representation of the object.

const jsonObj = { name: 'John', age: 30 };
const jsonString = JSON.stringify(jsonObj);
console.log(jsonString); // '{"name": "John", "age": 30}'

3. Can I use JSON.parse() with JSON data from an external API?

Yes, you can use JSON.parse() to parse JSON data received from an external API. When you receive JSON data from an API, it is usually in the form of a JSON string. You can use JSON.parse() to convert this JSON string into a JavaScript object that you can work with. However, ensure that you handle parsing errors using a try-catch block, as demonstrated earlier in this guide.

4. Can JSON data include functions or methods?

No, JSON data cannot include functions or methods. JSON is a data-interchange format and does not support executable code, such as functions or methods. JSON data can only include simple data types, such as strings, numbers, booleans, objects (key-value pairs), and arrays.

No, JSON data does not support comments. JSON is a data-interchange format and is designed to be as simple as possible. Including comments in JSON data would make it more complex and harder to parse, which goes against the design goal of JSON.

  • MDN Web Docs — JSON.parse()
  • JSONLint — The JSON Validator
  • MDN Web Docs — JSON.stringify()
  • Official JSON Website

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Понравилась статья? Поделить с друзьями:
  • Ошибка park brake ауди а6 с6
  • Ошибка park brake fault дискавери 3
  • Ошибка park assist service requ 106 volvo xc90
  • Ошибка parameter with name 86 not exist
  • Ошибка paper на принтере brother