Unhandled promise rejection syntaxerror json parse error unexpected identifier object

Hello. I am doing a project in react -native but when executing my project I am getting the following error: [Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier &quot...

Hello.

I am doing a project in react -native but when executing my project I am getting the following error:

[Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier "An"]

Stack trace:
  [native code]:null in parse
  node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
  node_modules/promise/setimmediate/core.js:123:25 in setImmediate$argument_0
  node_modules/react-native/Libraries/Core/Timers/JSTimers.js:146:14 in _callTimer
  node_modules/react-native/Libraries/Core/Timers/JSTimers.js:194:17 in _callImmediatesPass
  node_modules/react-native/Libraries/Core/Timers/JSTimers.js:458:30 in callImmediates
  [native code]:null in callImmediates
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:407:6 in __callImmediates
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:143:6 in __guard$argument_0
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
  node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:142:17 in __guard$argument_0
  [native code]:null in flushedQueue
  [native code]:null in invokeCallbackAndReturnFlushedQueue
  ...

My code is as follows:

App.js

import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import MealsScreen from './src/screens/Meals';
import Modal from './src/screens/Modal';

const AppNavigation = createStackNavigator({
  Meals: {
    screen: MealsScreen
  }
}, {
  initialRouteName: 'Meals'
});

const RootStack = createStackNavigator( {
  Main: AppNavigation,
  Modal: Modal,
}, {
  mode: 'modal',
  headerMode: 'none',
});

export default createAppContainer( RootStack );

Meals.js

import React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import ListItem from '../components/ListItem';
import UseFetch from '../hooks/useFetch';

const Meals = ({navigation}) => {
    const { loading, dato: meals } = UseFetch('https://serverless.mgyavega.now.sh/api/meals');

    return(
        <View style =  { styles.container }>
            { loading ? <Text>Cargando por favor espere...</Text> :
                <FlatList
                    style = { styles.list }
                    data = { meals }
                    keyExtractor = { x => x._id }
                    renderItem = { ({ item }) =>
                        <ListItem
                            onPress = { () => navigation.navigate('Modal', { id: item._id })}
                            name = { item.name }
                        />
                    }
                />
            }
        </View>
    )
}

Meals.navigationOptions = ({
    title: 'Comidas Disponibles',
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'flex-start',
        justifyContent: 'flex-start'
    },
    list: {
        alignSelf: 'stretch'
    }
});

export default Meals;

ListItem.js

import React from 'react';
import {  TouchableOpacity, Text, StyleSheet } from 'react-native';

export default ({ name, onPress }) => {

    return (
        <TouchableOpacity onPress = { onPress } style={ styles.container }>
            <Text style = { styles.text }> {name} </Text>
        </TouchableOpacity>
    )
}

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 15,
        height: 60,
        justifyContent: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#eee'
    },
    text: {
        fontSize: 16
    }
});

UseFetch.js

import React, { useState, useEffect} from 'react';

const UseFetch = ( url ) => {
    const [ loading, setLoading ] = useState(true);
    const [ dato, setDato] = useState([]); // Este traer al incio un arreglo vacio

    const fetchData = async () => {
        const response = await fetch(url);
        const data = await response.json();
        setDato(data);
        setLoading(false);
    }

    useEffect( () => {
        fetchData();
    }, []);

    return { loading, dato }
}

export default UseFetch;

Modal.js

import React from 'react';
import {  View, Text, } from 'react-native';
import UseFetch from '../hooks/useFetch';

export default ({ navigation }) => {

    const id = navigation.getParam('_id');
    const { loading, dato } = UseFetch(`https://serverless.mgyavega.now.sh/api/meals/${id}`);

    console.log( dato );

    return (

        loading ? <Text>Cargando </Text> :
            <View>
                <Text>  </Text>
                <Text> </Text>
            </View>

    )
}

I could not obtain the _id of the dishes in the Modal, when creating the console.log it indicates that the value is undefined, but when doing the console.log of the database in the method of the console.log modal (data) ; If you show me the data record but it first comes out empty and then the data in the record goes out twice, but in the execution, the error I indicated appears.

I appreciate the collaboration you can provide me.

Thank you.

Mari

Answer by Salvatore Hansen

Remove the JSON.parse line, because response is already parsed into an object by jQuery.,Making statements based on opinion; back them up with references or personal experience.,

Stack Overflow
Public questions & answers

,

Constructor not executed when deserializing JSON

Thus, your response is likely already an object. When you do JSON.parse(response), you’re really doing

JSON.parse("[object Object]")

Answer by Caden Salazar

I do not understand what went wrong when parsing file:

{ "t": -9.30, "p": 728.11, "h": 87.10 }
<script type="text/javascript">
function check() {
    ("#temp").html(json.t + "&deg;");
            ("#temp").html("error");
        }
    });
}
SyntaxError: JSON Parse error: Unexpected identifier "object"

Answer by Kristopher Espinoza

The JavaScript exceptions thrown by JSON.parse() occur when string failed
to be parsed as JSON.
,SyntaxError: missing ; before statement,SyntaxError: missing ] after element list,SyntaxError: JSON.parse: bad parsing

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
SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge)

Answer by Keenan Andrade

I do not understand what went wrong when parsing file:,2) Ensure the json has the property, and we’re not accessing keys we don’t want if (json.hasOwnProperty(key)),It looks like const myArray = await AsyncStorage.getItem(‘user’); is returning undefined while you defended yourself from null only, which is not sufficient here.,Some modern browsers have support for parsing JSON into a native object:

I do not understand what went wrong when parsing file:

{ "t": -9.30, "p": 728.11, "h": 87.10 }

javascript code:

<script type="text/javascript">
function check() {
    $.get("http://....file.json", function(response, status, xhr) {
        if (status == "success") {
            var json = JSON.parse(response);
            $("#temp").html(json.t + "&deg;");
            $("#pressure").html(json.p + " mm hg");
        }
        if (status == "error") {
            $("#temp").html("error");
        }
    });
}

I receive error:

SyntaxError: JSON Parse error: Unexpected identifier "object"

Answer by Noemi Lowe

As far as I can see in the debug script, the first error originates here:,
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
,

The text was updated successfully, but these errors were encountered:
,I’m seeing huge amount of such JS console errors throughout all our websites.

unhandled_error 
Object
env: "sandbox"
err: "Error: Invalid json: .↵    at XMLHttpRequest.<anonymous> (https://www.paypal.com/sdk/js?client-id=[XXXXXXXXXXXXXXXXX]&currency=EUR&locale=de_DE:2:40216)"
referer: "127.0.0.1:8080"
timestamp: "1603442005749"
uid: "ced90d620e_mdg6mzm6mjq"

Uncaught Error: Invalid json: .
    at XMLHttpRequest.<anonymous> (js?client-id=[XXXXXXXXXXXXXXXXX]&currency=EUR&locale=de_DE:2)

Answer by Dalton Barajas

When attempting to read a JSON formatted data in Hype, JSON Parse function raises an error as: Unexpected identifier “object”, even when the provided data is valid in other javascript frameworks, like Appcelerator.,why are you trying to parse a valid js as Json?
you’re first attempt sets var data to a array with one element that is a object. so data[0] in any hypefunction will return the object …,then I have a setup function to read and decode the data.js by doing:,So, question is why only this format is accepted in Hype when the other format still valid for pure javascript code?

in HTML header, I am including the corresponding line to load the data like .js file as follow:

<script type="text/javascript" src="${resourcesFolderName}/data.js"></script>

then I have a setup function to read and decode the data.js by doing:

//Get data from JSON file
     window.myData = JSON.parse(data);

with this format (data.js) it produces the above error:

   var data = [
    {"id":"1", 
    "question":"something",
    "answer":"D",
    "A":"Xmod_write",
    "B":"All",
    "C":"None",
    "D":"both a) and b)",
    "E":"a), b) and c)",
    "status":""}
  ];

If I change the file (data.js) as follow by adding ’ symbol:

var data = '[
        {"id":"1", 
        "question":"something",
        "answer":"D",
        "A":"Xmod_write",
        "B":"All",
        "C":"None",
        "D":"both a) and b)",
        "E":"a), b) and c)",
        "status":""}
      ]';

it produces the following error at parse:

SyntaxError: Unexpected EOF
Error in setup: ReferenceError: Can't find variable: data

and if I try pure JSON format as follow:

"data" : [
            {"id":"1", 
            "question":"something",
            "answer":"D",
            "A":"Xmod_write",
            "B":"All",
            "C":"None",
            "D":"both a) and b)",
            "E":"a), b) and c)",
            "status":""}
          ]

and this is the error produced:

SyntaxError: Unexpected token ':'. Parse error.
(anonymous function) data.js:1 HYPE-466.thin.min.js:14:99
Error in setup: ReferenceError: Can't find variable: data

However the only format that worked for me so far was:

data = '[{"id": "1", "question":"something", "answer": "D", "A": "Xmod_write", "B": "All", "C": "None", "D": "both a) and b)", "E": "a), b) and c)", "status": "noAnswered"},{"id": "2", "question":"something", "answer": "D", "A": "Xmod_write", "B": "All", "C": "None", "D": "both a) and b)", "E": "a), b) and c)", "status": "noAnswered"}]';

Answer by Cassius Russo

javascript — JavaScript中的简单货币换算
,
javascript — sessionStorage刷新初始屏幕
,
javascript — 在 native react 中生成多个APK?
,
原文
标签

javascript

jquery

json

我不明白解析文件时出了什么问题:

{ "t": -9.30, "p": 728.11, "h": 87.10 }

<script type="text/javascript">
function check() {
    $.get("http://....file.json", function(response, status, xhr) {
        if (status == "success") {
            var json = JSON.parse(response);
            $("#temp").html(json.t + "&deg;");
            $("#pressure").html(json.p + " mm hg");
        }
        if (status == "error") {
            $("#temp").html("error");
        }
    });
}

SyntaxError: JSON Parse error: Unexpected identifier "object"

Answer by Holland Torres

From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON.parse() function or use the .json() method on the fetch object, it can result in a JavaScript exception being thrown. But don’t worry, it’s not the end of the world and we can handle it. There can be different causes for this happening so let’s see what we can do about it.,
JSON Web Tokens are a useful tool and a better way of implementing authorization in web applications, but what exactly are they and how do they work?
,JSON format is quite similar to JavaScript objects, but it is not always the case. It is important to remember that every property name must be wrapped in double quotes.,JSON, which is an acronym for JavaScript Object Notation, is one of the most popular data formats used for transmitting data. It is a lightweight format and consists of name-value pairs. Values can be strings, arrays, or any other data that can be serialized.

Below you can see an example of a JSON format.

{
    "name": "animals",
    "animals": [
        "Dog",
        "Cat",
        "Mouse",
        "Pig",
        "Bear"
  ],
  "hobbies": {
        "football": false,
        "reading": true
  }
}

JSON format is quite similar to JavaScript objects, but it is not always the case. It is important to remember that every property name must be wrapped in double quotes.

// not valid JSON
{
  x: 4
}

// valid JSON
{
  "x": 4
}

“Unexpected token < in JSON at position 0” is the error that I have seen most throughout my time of working as a software developer. Quite often it happens in a situation when fetch function is used for sending an API request from a client. After receiving a response from a server, usually it is parsed to JSON.

fetch(‘url’).then(response => response.json())

The first thing to do in this situation is to confirm where the error is happening exactly. To ensure the error happens on the exact line we think it does, we can wrap the JSON parsing code in a try-catch block. Check the code below.

fetch("url").then(async response => {
      try {
       const data = await response.json()
       console.log('response data?', data)
     } catch(error) {
       console.log('Error happened here!')
       console.error(error)
     }
    })

In this example, we can see a JSON string sent from the swapi API, so it is correct. However, in a different case, the response could be in the XML format or the server could have sent an HTML file. The former could happen if you are dealing with a server that can return different responses depending on the content-type header provided. If this is the case, when you send a request, make sure you specify the content-type header as shown below:

fetch(‘url’, {
  method: ‘GET’,
  headers: {
    ‘Content-Type’: ‘application/json’
  }
}).then(response => response.json())

Answer by Alena Bryan

Troubleshoot ‘Uncaught SyntaxError: Unexpected token u in JSON at position 0’,The ‘Uncaught SyntaxError: Unexpected token u in JSON at position 0’ error is caused when the client has been asked to execute JSON.parse() on a string beginning with u instead of the stringified object it was expecting. Usually this is a stringified version of the undefined primitive.,To illustrate this idea, see that trying to parse an object property that you have not defined will also return this error. For example:,The error message can also occur if you’ve passed back a string that the application then tries to parse as if it were an object. Consider an example where you try to parse a string that begins with the letter u:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Содержание

  1. SyntaxError: JSON Parse error: Unexpected identifier «object» #14919
  2. Comments
  3. EXPLANATION OF THE ISSUE
  4. STEPS TO REPRODUCE THE ISSUE
  5. SYSTEM STATUS
  6. Server Environment
  7. Database
  8. Security
  9. Active Plugins (40)
  10. Settings
  11. WC Pages
  12. Theme
  13. Templates
  14. Elavon Converge Credit Card
  15. Elavon Converge eCheck
  16. [Solved] SyntaxError: Unexpected end of JSON input
  17. Fix 1: close the curly bracket
  18. Fix 2: use JSON.stringify() to make JSON strings
  19. Fix 3: use jsonlint to check your JSON
  20. Fix 4: catch the error
  21. Conclusion

SyntaxError: JSON Parse error: Unexpected identifier «object» #14919

EXPLANATION OF THE ISSUE

During checkout, when trying to place the order I receive «SyntaxError: JSON Parse error: Unexpected identifier «object»» at the top of the screen right below the gift card and coupon area.

STEPS TO REPRODUCE THE ISSUE

  1. Visit http://yazbeck.com
  2. Put something in the shopping cart.
  3. Fill out user form.
  4. Fill in fake credit card info and try to «place order».
  5. Error occurs.

SYSTEM STATUS

Home URL: http://yazbeck.com
Site URL: http://yazbeck.com
WC Version: 3.0.4
Log Directory Writable: ✔
WP Version: 4.7.4
WP Multisite: –
WP Memory Limit: 512 MB
WP Debug Mode: –
WP Cron: ✔
Language: en_US

Server Environment

Server Info: Apache
PHP Version: ❌ 5.4.16 — We recommend a minimum PHP version of 5.6. See: How to update your PHP version
PHP Post Max Size: 512 MB
PHP Time Limit: 500
PHP Max Input Vars: 1000
cURL Version: 7.29.0
NSS/3.15.4

SUHOSIN Installed: –
Max Upload Size: 512 MB
Default Timezone is UTC: ✔
fsockopen/cURL: ✔
SoapClient: ❌ Your server does not have the SoapClient class enabled — some gateway plugins which use SOAP may not work as expected.
DOMDocument: ✔
GZip: ✔
Multibyte String: ✔
Remote Post: ✔
Remote Get: ✔

Database

WC Database Version: 3.0.4
WC Database Prefix: ugAd5YM5q_
woocommerce_sessions: ✔
woocommerce_api_keys: ✔
woocommerce_attribute_taxonomies: ✔
woocommerce_downloadable_product_permissions: ✔
woocommerce_order_items: ✔
woocommerce_order_itemmeta: ✔
woocommerce_tax_rates: ✔
woocommerce_tax_rate_locations: ✔
woocommerce_shipping_zones: ✔
woocommerce_shipping_zone_locations: ✔
woocommerce_shipping_zone_methods: ✔
woocommerce_payment_tokens: ✔
woocommerce_payment_tokenmeta: ✔

Security

Secure connection (HTTPS): ❌ Your store is not using HTTPS. Learn more about HTTPS and SSL Certificates.
Hide errors from visitors: ✔

Active Plugins (40)

BackupBuddy: by iThemes – 7.1.5.1
AfterShip — WooCommerce Tracking: by AfterShip – 1.6.8
Boxzilla: by ibericode – 3.1.12
Comet Cache: by WebSharks
Inc. – 170220

Easy Testimonials: by Gold Plugins – 2.2.5
WooCommerce — Gift Cards: by WP Ronin – 2.5.8
Google Analytics Dashboard for WP: by Alin Marcu – 4.9.6.2
Google Doc Embedder: by Kevin Davis
Dan Lester – 2.6.2

Groups: by itthinx – 2.1.2
Hide Admin Bar From Non-admins: by Stranger Studios – 1.0
Instagram Feed: by Smash Balloon – 1.4.8
iThemes Sync: by iThemes – 1.175.0
MailChimp for WordPress: by ibericode – 4.1.1
MailChimp for WordPress — Top Bar: by ibericode – 1.2.16
Nextend Facebook Connect: by Nextendweb – 2.0.2
Nextend Google Connect: by Roland Soos
Jamie Bainbridge – 1.6.1

Ninja Forms reCAPTCHA: by Aman Saini – 1.2.5
Ninja Forms: by The WP Ninjas – 3.1.1
Q and A Focus Plus FAQ: by Lanexatek Creations – 1.3.9.7
Regenerate Thumbnails: by Alex Mills (Viper007Bond) – 2.2.6
Taxonomy Metadata: by mitcho (Michael Yoshitaka Erlewine)
sirzooro – 0.5

Ultimate Member: by Ultimate Member – 1.3.84
Ultimate Member — Google reCAPTCHA: by Ultimate Member – 1.0.3
WooCommerce Extended Coupon Features: by Soft79 – 2.4.3
WooCommerce Print Invoice & Delivery Note: by Triggvy Gunderson – 4.1.5
WooCommerce Elavon Converge Gateway: by SkyVerge – 2.1.1
WooCommerce Group Coupons: by itthinx – 1.7.0
WooCommerce Memberships: by SkyVerge – 1.8.4
WooCommerce Multiple Free Gift: by Ankit Pokhrel – 1.2.0
WooCommerce Sequential Order Numbers: by SkyVerge – 1.8.1
WooCommerce Table Rate Shipping: by Bolder Elements – 3.6.6
WooCommerce: by Automattic – 3.0.4 – 3.0.5 is available
WooSidebars: by WooThemes – 1.4.3
WooCommerce Helper: by WooCommerce – 1.7.2 – Network enabled
WP Instagram Widget: by Scott Evans – 1.9.8
WP-SpamShield: by Scott Allen – 1.9.9.9.8
Custom Product Tabs for WooCommerce: by YIKES
Inc – 1.5.13

YITH WooCommerce Ajax Search: by YITHEMES – 1.5.2
YITH WooCommerce Wishlist: by YITHEMES – 2.1.1
YITH WooCommerce Zoom Magnifier: by YITHEMES – 1.2.29

Settings

API Enabled: ✔
Force SSL: ✔
Currency: USD ($)
Currency Position: left
Thousand Separator: ,
Decimal Separator: .
Number of Decimals: 2
Taxonomies: Product Types: external (external)
grouped (grouped)
simple (simple)
variable (variable)

Taxonomies: Product Visibility: exclude-from-catalog (exclude-from-catalog)
exclude-from-search (exclude-from-search)
featured (featured)
outofstock (outofstock)
rated-1 (rated-1)
rated-2 (rated-2)
rated-3 (rated-3)
rated-4 (rated-4)
rated-5 (rated-5)

WC Pages

Shop base: #2659 — /shop/
Cart: #7 — /cart/
Checkout: #8 — /checkout/
My account: #9 — /my-account/

Theme

Name: Flatsome
Version: 3.3.5
Author URL: http://www.uxthemes.com/
Child Theme: ❌ – If you’re modifying WooCommerce on a parent theme you didn’t build personally
then we recommend using a child theme. See: How to create a child theme

Templates

Overrides: flatsome/woocommerce/archive-product.php
flatsome/woocommerce/cart/cart-empty.php
flatsome/woocommerce/cart/cart.php
flatsome/woocommerce/checkout/form-checkout.php
flatsome/woocommerce/checkout/form-coupon.php
flatsome/woocommerce/checkout/thankyou.php
flatsome/woocommerce/content-product.php
flatsome/woocommerce/content-product_cat.php
flatsome/woocommerce/content-single-product.php
flatsome/woocommerce/global/breadcrumb.php
flatsome/woocommerce/global/quantity-input.php
flatsome/woocommerce/global/wrapper-end.php
flatsome/woocommerce/global/wrapper-start.php
flatsome/woocommerce/loop/loop-end.php
flatsome/woocommerce/loop/loop-start.php
flatsome/woocommerce/loop/orderby.php
flatsome/woocommerce/loop/pagination.php
flatsome/woocommerce/loop/result-count.php
flatsome/woocommerce/loop/sale-flash.php
flatsome/woocommerce/myaccount/form-login.php
flatsome/woocommerce/myaccount/navigation.php
flatsome/woocommerce/notices/error.php
flatsome/woocommerce/notices/notice.php
flatsome/woocommerce/notices/success.php
flatsome/woocommerce/product-searchform.php
flatsome/woocommerce/single-product/photoswipe.php
flatsome/woocommerce/single-product/price.php
flatsome/woocommerce/single-product/product-image.php
flatsome/woocommerce/single-product/product-thumbnails.php
flatsome/woocommerce/single-product/related.php
flatsome/woocommerce/single-product/review.php
flatsome/woocommerce/single-product/sale-flash.php
flatsome/woocommerce/single-product/share.php
flatsome/woocommerce/single-product/short-description.php
flatsome/woocommerce/single-product/tabs/tabs.php
flatsome/woocommerce/single-product/title.php
flatsome/woocommerce/single-product/up-sells.php
flatsome/woocommerce/single-product-reviews.php
flatsome/woocommerce/single-product.php

Elavon Converge Credit Card

Environment: Production
Tokenization Enabled: ✔
Debug Mode: Off

Elavon Converge eCheck

Environment: Production
Debug Mode: Off
`

The text was updated successfully, but these errors were encountered:

Источник

[Solved] SyntaxError: Unexpected end of JSON input

The Javascript error “SyntaxError: Unexpected end of JSON input” happens when you try to use JSON.parse() on an incomplete JSON string. Check your string for missing curly brackets ( > ) and / or unclosed double-quotes.

In yet another installment of “why won’t my JSON parse?”, we have the incomplete JSON string. This error comes up a lot when receiving incomplete responses from the server and may not be entirely your fault. But it’s still probably a little your fault.

Below is an example of some offending code:

If we try to run this through a Node interpreter, we’ll get the following error:

Yikes! That looks scary. But what’s the problem here? Well, if you know anything about JSON, you’ll immediately see what the issue is: your JSON string contains an incomplete JSON object. What should end up parsing into an object with one property, foo , with the value of “bar”, is missing its closing curly bracket.

Fix 1: close the curly bracket

If we close that JSON object with a matching left curly bracket, our code will look like this instead:

Much better! But this is a super simple example. If you’re getting this on your production code, and your code is talking to an API, it’s a good bet the server is just sending you an incomplete response. This could be due to network trouble or some error on the server causing it to abort the connection mid-response.

Fix 2: use JSON.stringify() to make JSON strings

If you’re hard-coding your own JSON strings, you’re gonna have a bad time. That’s a computer’s job! Of course, JSON is so easy to write and read, it’s very tempting to make something like this right there in your sever-side (if your server is Node) or client-side code:

And then run into trouble later because, even though it looks correct, it’s not valid JSON. That’s because valid JSON only has double quotes, not single quotes. So then you figure “alright, I’ll just make ’em double quotes then!”. And you do something silly like this:

And in your haste, you forgot the closing double-quote for the “bar” value, and now you have the same old “SyntaxError: Unexpected end of JSON input” you started with. Why is this so hard!? Because you’re trying to speak a totally different language than Javascript… inside a string… inside Javascript. That’s like, a lot of work. And very error prone.

Did you know Javascript has a built-in function so you don’t have to do this? Bet you didn’t. It’s called JSON.stringify() and apart from having a cool name, it can make your life a whole lot easier.

See that? Perfect JSON every time. That’s why making and reading JSON is best left up to computers. Yeah, it’s a popular serialization format because it’s human readable. But that doesn’t mean it’s supposed to be human write-able

(I know, lots of config files are now written in JSON. Leave me alone)

Fix 3: use jsonlint to check your JSON

Linters are super useful. They make sure your code isn’t dumb before you try to do stuff with it. jsonlint is a node package that can help you check your JSON before you wreck your JSON.

Install it like this:

Create a JSON file with the same contents as our broken string in the first example and save it as foo.json:

Then run jsonlint like this:

And you should have some output like the following:

Now that is a bit more helpful than “SyntaxError: Unexpected end of JSON input”, don’t you think? Our example is, again, trivial, but with a more complex JSON object to debug, you can see how jsonlint would be very useful.

Fix 4: catch the error

If you are expecting that you might get bad JSON and you just want to avoid your whole program crashing, you can also catch the error very simply:

Here, we wrap the JSON.parse() call in a try / catch block so that we can print an error message instead of having an unhandled exception float to the top of our call stack and make us look like a bunch of amateurs. Note that we are also making sure the exception is an instance of a SyntaxError so we don’t inadvertently catch something else and think it was the JSON syntax error. It’s just good practice to be specific in what exceptions you catch.

Conclusion

In this article we covered what causes “SyntaxError: Unexpected end of JSON input” and how to fix it, prevent it, or handle it. Which one of the fixes above you choose depends on your application. Sometimes, you might be getting JSON from the user, and you can’t assume it’ll be valid. So in that case it’s better to catch the error and deal with it. Otherwise, if you’re debugging something your API is returning to you, you may want to consider jsonlint or something similar.

Hope this helped. Till next time!

About the Author

Bill is a senior software engineer with 23 years of experience. He specializes in Python, Javascript, C/C++, DevOps, test driven development, and making sure your code isn’t terrible.

Источник

Я только что переключился на Mac сегодня и заметил, что JSON.parse, который работает в других браузерах, выдает эту ошибку в сафари.

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

Это ответ JSON из моего PHP-кода

   {"dataPointsX": "["31 Jan","01 Feb","02 Feb","03 Feb","04 Feb","05 Feb","06 Feb"]", "dataPointsY": "["0","0","7287","24572","30657","27865","0"]", "dataPoints2Y": "["0","0","0","0","0","0","0"]"}

Это мой код Javascript

$.get('chartdata.php', async function (res) {
   console.log(res)
   var res = JSON.parse(res);
});

Пожалуйста помоги

ОБНОВИТЬ

Я обновил свой PHP, чтобы повторить это

{"dataPointsX":["31 Jan","01 Feb","02 Feb","03 Feb","04 Feb","05 Feb","06 Feb"],"dataPointsY":["0","0","7287","24572","30632","27820","0"],"dataPoints2Y":["0","0","0","0","0","0","0"]}

Он работает на хроме, сафари все еще выдает эту ошибку

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

Console.log(JSON.parse(res)) показывает это на хроме

dataPoints2Y: (7) ['0', '0', '0', '0', '0', '0', '0']
dataPointsX: (7) ['31 Jan', '01 Feb', '02 Feb', '03 Feb', '04 Feb', '05 Feb', '06 Feb']
dataPointsY: (7) ['0', '0', '7287', '24572', '30489', '27744', '0']
[[Prototype]]: Object

Похоже, ваш PHP-код представляет собой содержимое кодирования JSON, которое уже закодировано JSON, может быть, что-то вроде этого:

$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => json_encode($points)]);

Это дает странную строку в кавычках:

{"dataPointsX":"["31 Jan","01 Feb","03 Feb"]"}

Вы хотите вызвать json_encode() только один раз:

$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => $points]);


1

Alex Howansky
6 Фев 2022 в 02:52

Понравилась статья? Поделить с друзьями:
  • Unhandled exception произошла одна или несколько ошибок фазмофобия
  • Unhandled exception type segmentation error vmstate 0x00000000
  • Unhandled exception occurred see log for details dead air как исправить
  • Unhandled exception occurred see log for details call of chernobyl как исправить ошибку
  • Unhandled exception in the host library как исправить