Jquery json syntax error

Description: Load JSON-encoded data from the server using a GET HTTP request.

jQuery.getJSON( url [, data ] [, success ] )Returns: jqXHR

Description: Load JSON-encoded data from the server using a GET HTTP request.

  • version added: 1.0jQuery.getJSON( url [, data ] [, success ] )

    • url

      A string containing the URL to which the request is sent.

    • data

      A plain object or string that is sent to the server with the request.

    • success

      A callback function that is executed if the request succeeds.

This is a shorthand Ajax function, which is equivalent to:

Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL.

Most implementations will specify a success handler:

1

2

3

4

5

6

7

8

9

10

11

$.getJSON( "ajax/test.json", function( data ) {

$.each( data, function( key, val ) {

items.push( "<li id='" + key + "'>" + val + "</li>" );

This example, of course, relies on the structure of the JSON file:

1

2

3

4

5

"one": "Singular sensation",

"two": "Beady little eyes",

"three": "Little birds pitch by my doorstep"

Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function receives a «jqXHR» object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript’s object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see https://json.org/.

JSONP

If the URL includes the string «callback=?» (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

The jqXHR Object

As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or «jqXHR,» returned by $.getJSON() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

The Promise interface in jQuery 1.5 also allows jQuery’s Ajax methods, including $.getJSON(), to chain multiple .done(), .always(), and .fail() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

// Assign handlers immediately after making the request,

// and remember the jqxhr object for this request

var jqxhr = $.getJSON( "example.json", function() {

console.log( "success" );

console.log( "second success" );

console.log( "complete" );

// Perform other work here ...

// Set another completion function for the request above

jqxhr.always(function() {

console.log( "second complete" );

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Additional Notes:

  • Due to browser security restrictions, most «Ajax» requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Examples:

Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<title>jQuery.getJSON demo</title>

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

var flickerAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";

$.each( data.items, function( i, item ) {

$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );

Demo:

Load the JSON data from test.js and access a name from the returned JSON data.

1

2

3

$.getJSON( "test.js", function( json ) {

console.log( "JSON Data: " + json.users[ 3 ].name );

Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
If an error occurs, log an error message instead.

1

2

3

4

5

6

7

8

$.getJSON( "test.js", { name: "John", time: "2pm" } )

console.log( "JSON Data: " + json.users[ 3 ].name );

.fail(function( jqxhr, textStatus, error ) {

var err = textStatus + ", " + error;

console.log( "Request Failed: " + err );

The JavaScript exceptions thrown by JSON.parse() occur when string failed
to be parsed as JSON.

Message

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

Error type

What went wrong?

JSON.parse() parses a string as JSON. This string has to be valid JSON
and will throw this error if incorrect syntax was encountered.

Examples

JSON.parse() does not allow trailing commas

Both lines will throw a SyntaxError:

JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data

Omit the trailing commas to parse the JSON correctly:

JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');

Property names must be double-quoted strings

You cannot use single-quotes around properties, like ‘foo’.

JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data

Instead write «foo»:

JSON.parse('{"foo": 1}');

Leading zeros and decimal points

You cannot use leading zeros, like 01, and decimal points must be followed by at least
one digit.

JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data

JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data

Instead write just 1 without a zero and use at least one digit after a decimal point:

JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');

See also

If you have ever used the JSON.parse() method, then there’s a good chance that you have come across the following error at some point or another:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

This syntax error is thrown if you attempt to parse a JSON string that has already been parsed into a JavaScript object. i.e. The JSON.parse() method cannot be used to parse something that has already been parsed. It expects a JSON string and if you give it anything else, your code will fail.

Fixing the “Unexpected token o” error.

One method I’ve seen is to stringify the variable before attempting to parse it:

var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);

console.log(parsedObj);

In the JavaScript example above, we used the JSON.stringify() method to convert the data into a string before attempting to parse it. Note that this will not work if the data is already a string.

This leads me onto my next point.

All in all, it depends on what content type the server is returning. In some cases, the server will return Content-Type: application/json. In other cases, it will return a valid JSON string with Content-Type: text/html.

If you are using JQuery’s AJAX method and the server responds with a Content-Type of application/json, then you will not need to parse the JSON. This is because JQuery detects the content type and automatically parses it into a JavaScript object.

Take the following PHP script, for example:

<?php

header('Content-Type: application/json');

echo json_encode(array(
    'test' => true
));

The code above sets the correct Content-Type before printing the JSON string. This means that if we retrieve the JSON data via JQuery’s Ajax method, we will not have to parse it:

$.ajax({
    url: 'json.php',
    success: function(data){
        console.log(data);
    }
});

The JavaScript above will retrieve the JSON from our PHP script and then log the object to our browser’s console. In this particular case, we didn’t have to parse it into a JSON object because the PHP script in question is returning the correct Content-Type.

If we do attempt to parse the data, we will get a nasty “Unexpected token o in JSON” syntax error.

However, what if the server fails to give us the correct Content-Type? What if the server in question is responding with Content-Type: text/html?

<?php

echo json_encode(array(
    'test' => true
));

The PHP code above fails to specify any Content-Type. Therefore, it will default to “text/html“. As a result, we will need to tell our JavaScript code that it needs to parse the data into an object:

$.ajax({
    url: 'json.php',
    success: function(data){
        data = JSON.parse(data);
        console.log(data);
    }
});

As you can see, in this case, we did have to use the JSON.parse() method.

Another alternative is to tell JQuery what the data type is. We can use this by using the dataType setting:

$.ajax({
    url: 'json.php',
    dataType: 'json',
    success: function(data){
        console.log(data);
    }
});

In the AJAX request above, I specifically told JQuery that the returned data will be JSON. This means that I can avoid using the JSON.parse() method, even if the Content-Type is incorrect. Note that this will work, regardless of whether the Content-Type is application/json or text/html.

Hopefully, this post helped to solve your issue!

Понравилась статья? Поделить с друзьями:
  • Jquery get fail error
  • Jquery get error message
  • Jquery event error
  • Jquery error is not a function
  • Jquery ajax success error