Ошибка json parse unexpected character

I get this error:

JSON.parse: unexpected character

when I run this statement in firebug:

JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false});

Why is it so? The JSON string seems correct to me and I also tested it using JSHint. The passed object in the above case is a server response with content type set to application/json

Lucky's user avatar

Lucky

16.7k19 gold badges117 silver badges151 bronze badges

asked Dec 15, 2011 at 18:34

krishna's user avatar

0

You’re not parsing a string, you’re parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

answered Dec 15, 2011 at 18:37

kennytm's user avatar

kennytmkennytm

509k105 gold badges1078 silver badges1003 bronze badges

5

You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify() .

Updated your line below,

JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));

or if you have JSON stored in some variable:

JSON.parse(JSON.stringify(yourJSONobject));

June7's user avatar

June7

19.6k8 gold badges24 silver badges34 bronze badges

answered Feb 19, 2015 at 10:30

ScrapCode's user avatar

ScrapCodeScrapCode

2,0995 gold badges23 silver badges44 bronze badges

2

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

answered Jan 15, 2020 at 10:17

Lee's user avatar

LeeLee

29k27 gold badges114 silver badges169 bronze badges

$(document).ready(function(){
	var imagesCount = 0;
	var maxImages = 6;
	var imagesList = {};
$(function () {
      var $image = $('#image');

      $('#modal').on('shown.bs.modal', function () {
	$('.controls').hide();
	$('.progress').hide();
        $image.cropper({
          built: function () {
          }
        });
      }).on('hidden.bs.modal', function () {
	$('#submit-avatar-button').attr('disabled', 'true');
	$image.attr('src', '');
        $image.cropper('destroy');
      });
	$image.on('load', function(){
	    		$image.cropper({
			aspectRatio: 1,
			crop: function(data){
				var d = $image.cropper('getData');
				d.filename = $image.attr('src');
				$('#avatar-data').val(JSON.stringify(d));
			},
			dragMode: 'crop',
			autoCrop: true,
 			autoCropArea: 1,
			movable: false,
			scalable: false,
			zoomable: false,
			toggleDragModeOnDblclick: false,
			background: false,
			viewMode: 0,
			minCropBoxWidth: 100,
			minCropBoxHeight: 100
		});
                $('#submit-avatar-button').removeAttr('disabled');
	});
	$('.r_left').on('click', function(){
		$image.cropper('rotate', -90);
	});
	$('.r_right').on('click', function(){
		$image.cropper('rotate', 90);
	});

      $('#avatar-file').bind('change', function(){
	var data = new FormData();
	var error = '';
	jQuery.each($('#avatar-file')[0].files, function(i, file) {

            if(file.name.length < 1) {             	
               error = error + ' Файл имеет неправильный размер! ';             
            }
            data.append('file-'+i, file);
	});
	$.ajax({
	    url: '/modules/upload_resize.php',
	    data: data,
	    cache: false,
	    contentType: false,
	    processData: false,
	    type: 'POST',error: function (xhr, ajaxOptions, thrownError) {
//         	alert(xhr.responseText);
// 	        alert(thrownError);
	    },
	    xhr: function () {
	        var xhr =  $.ajaxSettings.xhr();
	        xhr.upload.addEventListener("progress", function (evt) {
	            if (evt.lengthComputable) {
	                var pB = $('.progress-bar'), percentComplete = evt.loaded / evt.total, progLabel = Math.round(percentComplete * 100) + "%";
	                pB.attr('style', 'width: '+progLabel);
			pB.text(progLabel);
	            }
	        }, false);
	        return xhr;
	    },
	    beforeSend: function () {
	        $('.progress').show();
		$('.controls').hide();
	    },
	    complete: function () {
		$('.progress-bar').text('Готово.');
	        $('.progress').delay(2000).fadeOut(500);
		$('.controls').show();
	    },
	    success: function(data){
		$image.cropper('destroy');
		$image.attr('src', data);
	    }
	});
	});
	$('#submit-avatar-button').on('click', function (){
		var imageList = $('#image_selection'), selectImage = imageList.children('#select');
		var data = $('#avatar-data').attr('value');
		$.ajax({
			url: '/modules/addavatar.php',
			data: {'avatar-data':data},
			type: 'POST',
			error: function(xhr, ajaxOptions, thrownError){
//         	alert(xhr.responseText);
// 	        alert(thrownError);
			},
			success: function(data){
				data = JSON.parse(data);
				var n = $('<li id="'+data.filename+'"></li>').insertBefore(selectImage);
				n.append('<img width="50" src="data:image/jpeg;base64,'+data.mini+'" />');
				imagesList[data.filename] = true;
				$('<button type="button" class="btn btn-danger pull-right">Удалить</button>').appendTo(n)
				.on('click', function(){
					imagesList[n.attr('id')] = false;
					n.remove();
					imagesCount--;
					if (imagesCount > 0){
						$('#sendimages').removeAttr('disabled');
					} else {$('#sendimages').attr('disabled', true);}
					$('#image-selection-button').show();
				});
				imagesCount++;
				if (imagesCount>=maxImages){
					$('#image-selection-button').hide();
				}
				if (imagesCount > 0){
					$('#sendimages').removeAttr('disabled');
				} else {$('#sendimages').attr('disabled', true);}
				$('button[data-dismiss="modal"]').click();
			}
		});
	});
	$('#sendimages').on('click', function (){
		$('form#hidden').children('input[type="hidden"]').attr('value', JSON.stringify(imagesList));
		$('form#hidden').children('input[type="submit"]').click();
	});
    });
});

function selectImage(){
	$('#avatar-file').click();
}

http://jsonlint.com/ Ошибку показывает:

Error: Parse error on line 1:
$(document).ready(fu
^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

, а как ее исправить не могу допереть. Главное на реальном хосте работает все.

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.parse is a method in JavaScript that is used to convert JSON data into JavaScript objects. However, while working with JSON data, developers may encounter the error «Unexpected Character at Line 1 Column 1 of JSON Data.» This guide will walk you through the steps to fix this issue.

Table of Contents

  1. Identifying the Issue
  2. Fixing the Issue
  3. Check for Syntax Errors
  4. Validate JSON Data
  5. Handle Server Responses Correctly
  6. Use JSON Lint
  7. FAQs
  8. Related Links

Identifying the Issue

The «Unexpected Character at Line 1 Column 1 of JSON Data» error usually occurs when there is an issue with the JSON data being parsed. This can happen due to various reasons, such as incorrect JSON syntax, encoding issues, or issues with the server response.

Fixing the Issue

Check for Syntax Errors

The first step in fixing this error is to check for syntax errors in your JSON data. JSON data must follow a specific syntax, which includes:

  • Using double quotes for both keys and string values
  • No trailing commas after the last value in an array or object
  • Properly nesting and closing arrays and objects

For example, the following JSON data would cause the «Unexpected Character» error because it uses single quotes instead of double quotes:

{
  'name': 'John Doe',
  'age': 30
}

To fix this, change the single quotes to double quotes:

{
  "name": "John Doe",
  "age": 30
}

Validate JSON Data

You can use online tools like JSONLint or JSON Formatter to validate your JSON data. These tools will help you identify any syntax errors or formatting issues in your JSON data.

If your JSON data is valid, you’ll see a message like «Valid JSON» or «JSON is valid.» If there are any issues with your JSON data, these tools will provide a detailed error message with the line and column number where the error occurred.

Handle Server Responses Correctly

If you’re working with JSON data fetched from a server, you might encounter the «Unexpected Character» error if the server response is not properly handled. For example, if the server returns an error message instead of JSON data, you’ll get this error when trying to parse the response.

To avoid this issue, make sure to check the server response before parsing it. Here’s an example using the Fetch API:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    // Process the JSON data
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Use JSON Lint

JSON Lint is a useful tool for validating JSON data and identifying any issues with the data. Paste your JSON data into the JSON Lint input box and click «Validate JSON» to see if there are any issues with your JSON data.

If there are any issues, JSON Lint will provide a detailed error message along with the line and column number where the error occurred.

FAQs

1. What is JSON.parse?

JSON.parse is a method in JavaScript used to convert JSON data into JavaScript objects. This allows developers to work with JSON data as if it were a normal JavaScript object.

2. What causes the «Unexpected Character at Line 1 Column 1 of JSON Data» error?

This error usually occurs when there is an issue with the JSON data being parsed. This can be due to syntax errors, encoding issues, or issues with the server response.

3. How can I check for syntax errors in my JSON data?

You can check for syntax errors in your JSON data by ensuring that it follows the correct JSON syntax, which includes using double quotes for keys and string values, not having trailing commas after the last value in an array or object, and properly nesting and closing arrays and objects.

4. How can I validate my JSON data?

You can use online tools like JSONLint or JSON Formatter to validate your JSON data. These tools will help you identify any syntax errors or formatting issues in your JSON data.

5. How do I handle server responses correctly when working with JSON data?

To handle server responses correctly when working with JSON data, make sure to check the server response before parsing it. This can be done using the Fetch API or other methods, ensuring that the response is valid JSON before attempting to parse it.

  • MDN: JSON.parse
  • W3Schools: JSON Introduction
  • JSONLint — The JSON Validator
  • JSON Formatter & Validator

Получаю ошибку SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
вот мой код

var result = {
    price: price.replace(/s/g, ''),
    number_order: number_order
};

result_json = JSON.stringify(result);

pink_btn2.addEventListener("click", function () {
    fetch('/api/order/order.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: result_json
    }).then(res => res.json());

});

PHP

$content = trim(file_get_contents("php://input"));
$data = json_decode($content,true);

var_dump($data) ;

Что я делаю не так?

SyntaxError: JSON.parse: bad parsing Breaking Your Code? Your JSON is Invalid

A refresher on the purpose and syntax of JSON, as well as a detailed exploration of the JSON Parse SyntaxError in JavaScript.

Traveling deftly through to the next item in our JavaScript Error Handling series, today we’re taking a hard look at the JSON Parse error. The JSON Parse error, as the name implies, surfaces when using the JSON.parse() method that fails to pass valid JSON as an argument.

In this article, we’ll dig deeper into where JSON Parse errors sit in the JavaScript error hierarchy, as well as when it might appear and how to handle it when it does. Let’s get started!

The Technical Rundown

  • All JavaScript error objects are descendants of the Error object, or an inherited object therein.
  • The SyntaxError object is inherited from the Error object.
  • The JSON Parse error is a specific type of SyntaxError object.

When Should You Use It?

While most developers are probably intimately familiar with JSON and the proper formatting syntax it requires, it doesn’t hurt to briefly review it ourselves, to better understand some common causes of the JSON Parse error in JavaScript.

JavaScript Object Notation, better known as JSON, is a human-readable text format, commonly used to transfer data across the web. The basic structure of JSON consists of objects, which are sets of string: value pairs surrounded by curly braces:

{
"first": "Jane",
"last": "Doe"
}

An array is a set of values, surrounded by brackets:

[
"Jane",
"Doe"
]

A value can be a string, number, object, array, boolean, or null.

That’s really all there is to the JSON syntax. Since values can be other objects or arrays, JSON can be infinitely nested (theoretically).

In JavaScript, when passing JSON to the JSON.parse() method, the method expects properly formatted JSON as the first argument. When it detects invalid JSON, it throws a JSON Parse error.

For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array or object value set. Notice in the first few examples above, we only use a comma to literally separate values from one another. Here we’ll try adding an extra, or «hanging», comma after our final value:

var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
var json = `
{
«first»: «Jane»,
«last»: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}

Note: We’re using the backtick (`) string syntax to initialize our JSON, which just allows us to present it in a more readable form. Functionally, this is identical to a string that is contained on a single line.

As expected, our extraneous comma at the end throws a JSON Parse error:

[EXPLICIT] SyntaxError: Unexpected token } in JSON at position 107

In this case, it’s telling us the } token is unexpected, because the comma at the end informs JSON that there should be a third value to follow.

Another common syntax issue is neglecting to surround string values within string: value pairs with quotations ("). Many other language syntaxes use similar key: value pairings to indicate named arguments and the like, so developers may find it easy to forget that JSON requires the string to be explicitly indicated using quotation marks:

var printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}

try {
var json = `
{
«first»: «Jane»,
last: «Doe»,
}
`
console.log(JSON.parse(json));
} catch (e) {
if (e instanceof SyntaxError) {
printError(e, true);
} else {
printError(e, false);
}
}

Here we forgot quotations around the "last" key string, so we get another JSON Parse error:

[EXPLICIT] SyntaxError: Unexpected token l in JSON at position 76

A few examples are probably sufficient to see how the JSON Parse error comes about, but as it so happens, there are dozens of possible versions of this error, depending on how JSON was improperly formatted. Here’s the full list:

JSON Parse Error Messages
SyntaxError: JSON.parse: unterminated string literal
SyntaxError: JSON.parse: bad control character in string literal
SyntaxError: JSON.parse: bad character in string literal
SyntaxError: JSON.parse: bad Unicode escape
SyntaxError: JSON.parse: bad escape character
SyntaxError: JSON.parse: unterminated string
SyntaxError: JSON.parse: no number after minus sign
SyntaxError: JSON.parse: unexpected non-digit
SyntaxError: JSON.parse: missing digits after decimal point
SyntaxError: JSON.parse: unterminated fractional number
SyntaxError: JSON.parse: missing digits after exponent indicator
SyntaxError: JSON.parse: missing digits after exponent sign
SyntaxError: JSON.parse: exponent part is missing a number
SyntaxError: JSON.parse: unexpected end of data
SyntaxError: JSON.parse: unexpected keyword
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: end of data while reading object contents
SyntaxError: JSON.parse: expected property name or ‘}’
SyntaxError: JSON.parse: end of data when ‘,’ or ‘]’ was expected
SyntaxError: JSON.parse: expected ‘,’ or ‘]’ after array element
SyntaxError: JSON.parse: end of data when property name was expected
SyntaxError: JSON.parse: expected double-quoted property name
SyntaxError: JSON.parse: end of data after property name when ‘:’ was expected
SyntaxError: JSON.parse: expected ‘:’ after property name in object
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property value in object
SyntaxError: JSON.parse: expected ‘,’ or ‘}’ after property-value pair in object literal
SyntaxError: JSON.parse: property names must be double-quoted strings
SyntaxError: JSON.parse: expected property name or ‘}’
SyntaxError: JSON.parse: unexpected character
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.

An Easier Way to Find JavaScript Errors

The first way to find a JSON Parse error is to go through your logs, but when you’re dealing with hundreds, if not thousands, of lines of code, it can be difficult to find that one line of broken code. With Airbrake Error and Performance Monitoring, you can skip the logs and go straight to the line of broken code resulting in the JSON Parse error.

Don’t have Airbrake? Create your free Airbrake dev account today!

Try Airbrake, Create a Free Dev Account

Note: We published this post in February 2017 and recently updated it in April 2022.

Понравилась статья? Поделить с друзьями:
  • Ошибка kernel power код события 41 категория задачи 63
  • Ошибка kernel eventtracing как исправить
  • Ошибка json parse error unrecognized token
  • Ошибка kernel power код 41 в windows причины
  • Ошибка kernel event tracking код 2