Error json parse error undefined

I tried to parse json file in node but there always error and I google it but cannot solve it . Can you help me? undefined:1 undefined ^ SyntaxError: Unexpected token u at Object.parse (native) at

I tried to parse json file in node
but there always error
and I google it but cannot solve it .
Can you help me?

undefined:1
undefined
^
SyntaxError: Unexpected token u
at Object.parse (native)
at Object.<anonymous> (app.js:13:19)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

this’s my code

var app = express();
var mongodb = require("mongoskin");
var fs = require('fs');

var content;
fs.readFile('./config/db.json', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
var config = JSON.parse(content);


app.get('/', function(req, res){
    res.send(config.left);
});

app.listen(process.env.VCAP_APP_PORT || 3000);

and the db.json is this. As you can see, there are no errors.

{
  "left": 3
}

asked Mar 4, 2013 at 10:11

pan.mingzhi's user avatar

0

readFile is asynchronous, so your JSON.parse line is called before you assign a value to content, and so content has its default value of undefined.

You have two options:

  1. Move the logic using the data into the callback.

    var app = express();
    var mongodb = require("mongoskin");
    var fs = require('fs');
    
    fs.readFile('./config/db.json', function read(err, data) {
        if (err) {
            throw err;
        }
    
        var config = JSON.parse(data); // <=== Note I'm using `data`, not `content`; we don't need a `content` variable anymore
    
        app.get('/', function(req, res){
            res.send(config.left);
        });
    
        app.listen(process.env.VCAP_APP_PORT || 3000);
    });
    
  2. Use the synchronous version of readFile (which is readFileSync).

    // ...
    content = fs.readFileSync('./config/db.json');
    
    var config = JSON.parse(content);
    // ...
    

answered Mar 4, 2013 at 10:16

T.J. Crowder's user avatar

T.J. CrowderT.J. Crowder

1.0m184 gold badges1874 silver badges1836 bronze badges

0

content is equal to undefined when you try to parse it.
You should parse your JSON data in the readFile callback or use readFileSync instead.

Also you should probably not throw from a callback.

This leads me to think that you have some misconceptions of how node.js works and I strongly recommend you read this

answered Mar 4, 2013 at 10:18

Floby's user avatar

FlobyFloby

2,29617 silver badges15 bronze badges

Now that you know some more about JSON.stringify; let’s dive into its complement: JSON.parse.

The JSON parse function takes in a string (invalid JSON will cause a SyntaxError exception). If parsing succeeds, JSON.parse returns the corresponding value or object.

let value = JSON.parse("1");
console.log(value);
// 1

2. The reviver function

JSON.parse accepts an optional reviver function. This reviver function, if specified, allows you to carry out custom actions while parsing the retrieved JSON.

For example, say you want to process JSON values coming in from the server. You could parse the string and then modify it or write an interceptor that transforms the string during JSON.parse. In some scenarios, having this in JSON.parse is a neater approach.

A trivial example might be having a custom logger that invokes console.log during JSON.parse operations (you want to know what is coming over the wire when in debug mode) .

let logger = (key, value)
=> console.log(`${key} : ${value}`);
JSON.parse('{"a":1, "b":2}', logger);
//
// a : 1
// b : 2
//   : [object Object]

Usage

The reviver function accepts key and value parameters corresponding to each key-value-pair in the object.

Notes

1. The returned value for the input key will replace the original value in the JSON string.

let isOdd = (a) => !!(a & 1);
let jsonStr = '{"a":3, "b":2}';
let reviver = (key, value) => {
    if(isOdd(value)){
        return 2 * value;
    }
    return value;
};
let output = JSON.parse(jsonStr, reviver);
console.log(output);
// { a: 6, b: 2}

2. Inner properties are processed before outer properties.

let logger = (key, value) => console.log(`${key} : ${value}`); let output = JSON.parse('{"a":1, "b":2, "c": {"d": 4}}', logger);

3. Return undefined to filter out values. If you don’t want to change a value, you must return it. Otherwise, it’ll vanish in the converted object.

Note: JavaScript functions return undefined by default unless when invoked with the new keyword.

let jsonStr = '{"a":3, "b":2}';
let reviver = (key, value) => undefined;
let output = JSON.parse(jsonStr, reviver);
console.log(output);
// undefined

4. It is possible to transform the entire object; however, this requires some more processing. The last argument passed to the reviver function is the entire object and the key is an empty string (see picture in point 2).

The conundrum is that empty strings are also valid keys in JSON; now if you have a reviver function that removes values with the “” key, you risk losing the entire object. This should not be a problem though but knowing this edge case can help while debugging.

let jsonStr = '{"a":3, "b":2}';
let reviver = (key, value) => {
    if(key !== ""){
        return value;
    }
};
let output = JSON.parse('{"a":1, "b":2}', reviver);
console.log(output);
// undefined

4. Safe parser – TryParse

JSON.parse throws if invoked with invalid JSON and this can cause strange bugs. This problem happens often especially with the preponderance of JavaScript frameworks. At least, I have run into it while using Angular1 and Angular2.

Here is a sequence of steps that can trigger this scenario:

1. The 4XX and 5XX class of HTTP errors have optional response bodies so it is OK for a server to return a 400 with no body

2. The client side code expects a JSON body. For example, Angular2‘s HttpClient.get defaults to the JSON type.

3. Frameworks might use JSON.parse deep down in their stack (both Angular1 and Angular2 do this).

4. If the body is empty, then JSON.parse() throws and the error bubbles up the stack.

5. Fix?

  1. Have the server return valid JSON in the body of all requests
  2. Retrieve the HTTP response and then try to safely parse. A trivial safe parser that returns null for invalid input looks like this:
function tryParse(input) {
    try {
        JSON.parse(input);
    } catch (e) {
        return undefined;
    }
}
let b = tryParse('{');
console.log(b);
//undefined

I choose to return undefined whenever JSON.parse throws for two reasons:

  1. This allows for handling null values. The string “null” is valid JSON.
  2. Undefined is not a value in the JSON grammar

5. Gotchas

  • Comments invalidate JSON, there are some workarounds like repeating the same key to override earlier values but I am not so convinced
  • Serializing dates can be an issue, the workaround is to use timestamps which I think helps removes the overhead. In one of my past teams, we had to use a custom date time string representation which had to be parsed on the client specially.

Conclusion

I just realized I wrote the first part almost exactly a year ago; this complement has lived for an extremely long time as an unpublished draft because I needed to polish it.

Published
February 26, 2018September 23, 2021

Author: Chukwuka Reuben

Introduction.

This post aims to address the «Unexpected token in JSON at position 0» error message. We will look into the various possible causes of this message and suggest methods to rectify it.

Steps we’ll cover:

  • What is JSON?
  • What does the «Unexpected token < in JSON at position 0» error mean?
  • Different Reasons Why You Might Have This Error and Their Fixes.
  • Hitting Any API endpoint that does not exist:
  • Spelling Error
  • Forgetting to stringify your object:

What is JSON?

JSON which stands for Javascript Object Notation can be said to be a lightweight format for storing and transporting data, it is used often when data is sent from a server to a webpage.

If you have ever utilized API endpoints in your projects before, there’s a very high chance that JSON is being used to store and transport data between your web page and servers.

Let us quickly examine the utilization of JSON for transporting and storing data. We don’t need to look too far since the local storage on our internet browsers can function as servers.

The codeblock below shows how JSON can be used to transport data between local storage and the web page:

localStorage.setItem('list', JSON.stringfy(list))

JSON.parse(localStorage.getItem('list'))

Enter fullscreen mode

Exit fullscreen mode

Now that we are aware of what JSON is and how it can be applied, let us move on to resolving the «Unexpected token in JSON at position 0» error message.

What does the «Unexpected token < in JSON at position 0» error mean?

In very simple language, «Unexpected token < in JSON at position 0» indicates that you are parsing something else that is not JSON as JSON.

To prove my point, I will attempt to reproduce the mistake. Go to your browser console and execute this code snippet:

JSON.parse(undefined)

Enter fullscreen mode

Exit fullscreen mode

The code snippet above will produce this type of error:

json error description

Why? because «undefined» is not JSON but we have tried to parse it as JSON.

There’s something I would like you to note before we proceed:

The actual «Unexpected token in JSON at position 0» message may vary depending on what your server generates, however, the fundamental reason remains the same: you are attempting to parse something that is not JSON as JSON.

Below are some of the different forms in which the error message could be presented:

  • » is not a valid JSON at JSON.parse».

  • Unexpected token ‘<‘, «<!DOCTYPE «… is not valid JSON.

  • Unexpected token ‘o’, «not found!» is not valid JSON.

  • Unexpected token ‘o’, «[object obj… is not valid JSON»

and so on. So going forward I’ll be using the general name «JSON.parse unexpected token» to refer to this error.

Now that we know what the «JSON.parse unexpected token» error means, let us proceed to know the different reasons why you might have this error and also look into ways to fix them.

Different Reasons Why You Might Have This Error and Their Fixes.

In this section of this article, 4 reasons and their fixes will be listed:

Hitting Any API endpoint that does not exist:

This is one of the most common causes of this error, and this tends to occur during the fetch request in javascript.

As you might have already assumed, yes! it occurs when you’re trying to parse an endpoint result that is not JSON as JSON.

In this part of the article, we will consider two brief cases — one to obtain a valid endpoint and show the outcome, and the other to retrieve an endpoint that doesn’t exist so we can reproduce the error message.

Example 1:

In this example, I’ve used the JSON endpoints from https://dummyjson.com/, a place where you can get fake JSON data to use during development.

I’ve picked a valid endpoint from this site and went ahead to call the javascript fetch method on it, check out the code snippet and its result below:

fetch('https://dummyjson.com/products/1')
  .then(res => res.json())
  .then(json => console.log(json))

Enter fullscreen mode

Exit fullscreen mode

Using the code snippet above, I want to clarify that JSON.parse() is being done by res.json() under the hood.

error description

The image above shows that we got a valid JSON response, now let us move to the second example.

Example 2:

fetch("https://dummyjson.com/myProduct/1")
    .then((res) => res.json())
    .then((json) => console.log(json));

Enter fullscreen mode

Exit fullscreen mode

https://dummyjson.com/myProduct/1 that has been used as our API is an endpoint that I made up, so it is not a valid API endpoint and as you know parsing it will be you trying to parse something that isn’t JSON, as it is not a formatted JSON.

error description

How To Fix.

  • Make sure you are using a valid API endpoint:

    To make sure you are using a valid JSON endpoint, use JSONFORMATTER to verify your endpoints before using it.

  • Always use the try-and-catch within your fetch method or function to prevent your app from crashing.

Spelling Error

This is so much similar to hitting the wrong API, only that you might have been pretty sure that the API endpoint exists.

Spelling error tends to happen due to typographical error or maybe you don’t know what the correct spellings are.

Spelling errors do not apply only to API endpoints, they can also occur while attempting to fetch information from your local storage and lead to the «JSON.parse unexpected token» error message showing up.

How To Fix.

  • Check and proofread well before hitting the API.

  • Make sure you verify your API before hitting it. use JSONFORMATTER.

  • Use the try-and-catch method in your function to prevent your app from crashing.


Building a side project?

Meet the headless, React-based solution to build sleek CRUD applications. With refine, you can build complex projects without having advanced frontend skills.

Try refine to rapidly build your next CRUD project, whether it’s an admin panel, dashboard, internal tool or storefront.

refine blog logo


Forgetting to stringify your object:

If we don’t use the JSON.stringify() technique to convert our object into a string before sending it to a server, then we may encounter the error «JSON.parse unexpected token». This raises the question, «why is it necessary to transform our object into a string before sending it to a server?»

When sending data to a web server, the data has to be a string and to convert a javascript object to a string JSON.stringify() does the trick.

We are going to take two quick examples in this section, example 1 will represent the problem and example 2 will be the solution.

Example 1

Note:

Local storage will stand as our servers in this example.

I have a list of todos that I have written on my web page, I wish for them to stay even after I have reloaded my page*,* how do I make that happen?

I have to send those lists as data to my server, and then to retrieve them whenever I reload the page.

localStorage.setItem("list", 
list);

Enter fullscreen mode

Exit fullscreen mode

In the code snippet that I have provided, I have sent my data to the server without converting the object to a string using JSON.stringify(). Let’s take a look at the consequence this will have on our page, below is the code snippet for retrieving the list, and an image of the result:

const getLocalStorage = () => {
  let list = localStorage.getItem("list");
  if (list) {
    return (list = JSON.parse(localStorage.getItem("list")));
  } else {
    return [];
  }
};

Enter fullscreen mode

Exit fullscreen mode

error description

The error indicates that I’m trying to parse an object, and it’s not a valid JSON.

Example 2(The fix):

All we have to do to fix this error is to stringify our list before sending it to the server:

localStorage.setItem("list", 
JSON.stringify(list))

Enter fullscreen mode

Exit fullscreen mode

The code snippet above will fix the error.

In general, it is always a good idea to carefully check your JSON data for any syntax errors before attempting to parse it. This will help to ensure that your code is able to properly handle the JSON data and avoid any errors like the «Unexpected token in JSON at position 0» error.

Содержание

  1. Troubleshoot ‘Uncaught SyntaxError: Unexpected token u in JSON at position 0’
  2. Error Message
  3. Issue
  4. Resolving the Issue
  5. Returning undefined
  6. Trying to Parse a String
  7. Related Errors
  8. Attempting to Parse Unstringified Data
  9. Trying to Parse an HTML Document
  10. Bonus Tip: Using JSON Methods to Copy an Object
  11. javascript — JSON Parse error: Unexpected identifier «undefined»
  12. Answer
  13. Solution:
  14. Share solution ↓
  15. Additional Information:
  16. Didn’t find the answer?
  17. Similar questions
  18. Write quick answer
  19. About the technologies asked in this question
  20. JavaScript
  21. Welcome to programmierfrage.com
  22. Get answers to specific questions
  23. Help Others Solve Their Issues
  24. [Solved] SyntaxError: Unexpected end of JSON input
  25. Fix 1: close the curly bracket
  26. Fix 2: use JSON.stringify() to make JSON strings
  27. Fix 3: use jsonlint to check your JSON
  28. Fix 4: catch the error
  29. Conclusion

Troubleshoot ‘Uncaught SyntaxError: Unexpected token u in JSON at position 0’

• Published October 24, 2019 • Last updated September 3, 2021 • Written by Steve Goldberg
Applies to SuiteCommerce and all versions of SuiteCommerce Advanced
Takes about 6 minutes to read

Caution: this content was last updated over 1 year ago

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.

The most likely underlying cause is that server-side code that normally generates and returns the stringified JSON malfunctioned. There are many reasons for this, but you should start by examining the server-side code and checking, for example, what inputs it is receiving, how it generates the object and stringifies it, and when it is being called to send a response to the client.

It is important to keep in mind that the error itself is a generic JavaScript runtime error. However, in the context of NetSuite and SuiteCommerce, it is usually because you have written a function within a service or service controller that fetches record data, and that function has then malfunctioned and sent back an unset variable.

Error Message

Let’s start with how it looks. You may get the following error either in your web developer console, or, more likely, in NetSuite via the SSP application execution log:

JSON.parse() is designed to be used in conjunction with JSON.stringify to send objects converted to strings between client and server. Parsing is a transformation process by the recipient to convert the string to an object. “Position 0” refers to the first character in the string, which should be an opening curly brace ( < ); if it is not this character, it will immediately halt parsing and throw an exception.

Issue

Typically this occurs when you are working on a service file, where you are connecting to NetSuite and then requesting some data. When dealing with transmissions to and from the web store, data is usually in the form of an object. At various stages this data will be stringified (ie converted from an object to a string) or parsed (converted from a string to an object) and this will be where this error surfaces.

If you attempt to parse something other than an object, the JavaScript processor will usually fail. As it’s expecting an object, it will stop at the exact point where it is failing, which is why it’ll return the position where it got stuck. An unexpected token simply means that it was expecting data, but instead got a command keyword (but this error can be triggered by things like strings too because of how they’re being told to be used).

If the unexpected token is a u and it is position 0 (ie the first character) then that means it tried to parse something that begins with a u. And what familiar keyword in JavaScript begins with a u?

In other words, if you got the error message in the title of this post then the chances are you’ve told the JavaScript processor to run the following:

Try this out in your browser’s developer console to see what I mean.

Resolving the Issue

So, we know what’s happening. But why is it happening? Let’s look at some of the possible causes.

Returning undefined

Now, you probably haven’t told it to explicitly return undefined so that it can then attempt to parse it (why would you?) but the likelihood is that you have told your model, service or service controller to return a value to the frontend of your site but that value has not been successfully passed. You’ve done something like, «Return the value of variable foo» but have messed it up.

To check this, inspect (or log!) what you’re returning:

  • Is it an object?
  • Does it have properties and have you called one that actually exists?
  • Do those properties have values?
  • Are there typos in your code, such as a misspelled name?

To illustrate this idea, see that trying to parse an object property that you have not defined will also return this error. For example:

If your code looks good, keep in mind that this could also happen if you’ve returned a variable before its value (an object) has been generated. In these cases, make sure any required operations have finished. For example, if your object will be generated after a promise has resolved, make sure it has been resolved before it is passed back. If the promise is failing, make sure it is set up to return an object that contains an error message!

Remember, if you’re going to try and log an object to the SSP application log, you will need to stringify it first, otherwise you will just get [object Object] in the log.

Trying to Parse a String

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:

There are a couple of other errors that look similar to this one.

Attempting to Parse Unstringified Data

Another important thing to keep in mind is that before JSON can be parsed it must first be stringified. Now, modern service controllers are set up to detect when ‘complex’ data is being sent, so it will automatically try to stringify an array or object that is being sent back. For whatever reason, this may not be happening so you will need to track down the specific part in your code and see what’s going on.

Alternatively, you may be used to using service controllers and not realizing that you need to do this operation manually if you’re writing a custom .ss file, or if you’re writing something like a Suitelet.

In other words, you may have sent your object back well-formed and correct, but it’s not been stringified first, and the receiving part of the application has been told to parse the response. If it gets an unstringified object back, and it tries to parse it, it will fail.

To illustrate this, consider this example:

Trying to Parse an HTML Document

In some cases, a full HTML error page is generated and that is sent back instead of the desired value. When this happens, you’ll see something like this:

There is usually a very specific reason why this happened, that depends on your circumstances. Generally speaking, however: you’ve tried to request something, the server has failed, and, rather than return an object, it’s generated a full HTML error page and sent that back. The reason why there’s a character at the start is because it’s always the first character in a HTML page’s source. In most cases, it will be .

Therefore, if you want to troubleshoot this error, take a look at your browser’s Network tab in the developer tools and see what page it is sending back to you. It will usually have an error message in the body of the HTML.

Bonus Tip: Using JSON Methods to Copy an Object

Finally, a fun tip that relates to JSON.parse() and JSON.stringify() : if you’ve ever wanted to deep copy an object such that an object’s values are copied across to a new object by value rather than by reference, you can use JSON.parse(JSON.stringify(obj)) , where obj is your object.

For the record, you should use our built-in _.deepCopy() method in almost all cases because we account for certain situations where deeply copying an object can be problematic (such as with a Backbone model).

Anyway, what stringifying and immediately parsing does is convert the object to a string, thereby converting the properties and resolved values of the entire object to a string (and therefore terminating their pointers’ connections) and then converts it back to an object that you can use. This can be super helpful when you want to create a copy of an object as it is in that point in time:

From a performance perspective, it’s actually pretty quick, and it certainly saves you the hassle of writing a loop.

Источник

javascript — JSON Parse error: Unexpected identifier «undefined»

i just switched to a mac today and i noticed the JSON.parse that works on other browsers, throws this error on safari.

This is the JSON response from my PHP code

This is my Javascript code

I have updated my PHP to echo this

It works on chrome, safari still throwing this error

Console.log(JSON.parse(res)) shows this on chrome

Answer

Solution:

It looks like your PHP code is JSON encoding content that’s already JSON encoded, maybe something like this:

This yields the oddly quoted string:

You only want to call json_encode() once:

Additional Information:

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Similar questions

Find the answer in similar questions on our website.

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

About the technologies asked in this question

PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/

JavaScript

JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/

Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Источник

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

Источник

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.parse(), as the Javascript standard specifies.

Using JSON.parse()

Javascript programs can read JSON objects from a variety of sources, but the most common sources are databases or REST APIs. A JSON object read from these sources enters a Javascript program in a “flat” string format that contains the object’s key-value pairs.

To create a valid string variable, you must surround the JSON string with single quotes.

let flatJSON = '{"a": "b", "c": 1, "d": {"e": 2}}';

JSON.parse() requires one parameter: the flat JSON string to be converted into a JSON object. JSON.parse() takes the flat JSON string directly or as a Javascript variable. Passing variables is easier and more readable than passing in a long flat JSON string.

JSON.parse('{"a", "b", "c", 1}');
let flatJSON2 = '{"a": "b", "c": 1, "d": {"e": 2}}';
JSON.parse(flatJSON2);

JSON.parse() takes an optional second parameter which is called a “reviver.” A reviver is a function that converts the JSON data that JSON.parse() cannot process by itself. This reviver function example handles undefined values:

let flatJSON3 = ‘{“a”: “b”, “c”: 1, “d”: {“e”: 2}}’;
let reviver = function(key, value) {
    if(typeof value === 'undefined') { return null; }
;

let parsed = JSON.parse(flatJSON3, reviver);

Revivers convert empty values and complex objects into valid Javascript objects. The next section goes into the specifics of how this is done with common examples.

JSON.parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code.

If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands. This process is prone to error and often causes problems with the converted code’s scope.

Revivers have the specific purpose of converting string data into valid Javascript types. You should make conversions within reviver functions as simple as possible. In rare cases, a specialized conversion might require a lot of calculations.

Handling JSON.parse() Special Cases with Revivers

Error Handling

Improperly-formatted data passed to JSON.parse() raises an error, stops processing, and returns no processed data, even if the rest of the JSON is correct. If an error occurs, never assume that JSON.parse() returns a specific value.

Depending on how you write your program, an error could stop the rest of your Javascript code from executing. Wrap calls to JSON.parse() in a try catch statement so you can explicitly specify what happens if parsing fails.

try {
    JSON.parse(input);
} catch (e) {
    return undefined; // Or whatever action you want here
}

Array Data

JSON.parse() converts array data into a Javascript array. The array data must be a valid JSON string.

This is an uncommon use for JSON.parse(). It’s easier to declare an array in code instead of going through JSON first. Declare arrays inside your Javascript program whenever possible.

Dates

Dates are not a valid JSON type. Converting strings of a particular format into a Javascript date type is a common extra step after using JSON.parse(). Several examples are shown below.

A reviver function that converts strings to dates may look like this, if using ISO standard date format:

function reviver(key, value) {
    if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
        return new Date(value);
    }
}

The Javascript Date object translates various string formats into dates. Always check whether the resulting date makes sense, even if the Date object “understood” its format. Here’s an example of a string conversion that results in an invalid real-world date:

// Converted to valid date: 02/16/2021
let date1 = JSON.parse('{"test": "2021-02-16"}');

// Converted to invalid date: 02/30/2021
let date2 = JSON.parse('{"test": "2021-02-30"}');

Empty Values

Null values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON. JSON.parse() will fail if it encounters an undefined value.

Searching for undefined values in a JSON string is a possible workaround for this problem, but be careful not to match any instances of the word “undefined” in a string. A better solution is to search for and replace the undefined value with a similar empty value type:

let parsedVal = (typeof value === 'undefined') ? null : value;

Using JSON.parse() Safely

Wrap JSON.parse() in a function to cover its limits, handing special cases appropriate to your needs. Include a reviver function in a closure to handle common data conversion needs.

When you need more specialized data conversion than your default reviver function can handle, add a second reviver function as a parameter to your safe parsing function. Call the second reviver function at the end of the default reviver function.

Putting all of this together with previous code examples, here’s a simple safe JSON parsing function:

function safeJsonParse(json, reviver) {
    function defaultReviver(key, value) {
        if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
            return new Date(value);
        }

        if(typeof value === 'undefined') { return null; }
        if(reviver !== undefined) { reviver(); }
    }

    try {
        let json = JSON.parse(json, defaultReviver);
    } catch(e) {
        return null;
    }
}

Conclusion

JSON.parse() is a crucial method for converting JSON data in string form into Javascript objects. It is possible to convert simple or complex objects, but you should never convert calculations or code, like for loops.

Enroll in our Intro to Programming Nanodegree Program today to learn more about JSON parsing with JSON.parse() and other programming concepts.

Start Learning

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 
SyntaxError: JSON.parse: expected 
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 
SyntaxError: JSON.parse: expected 
SyntaxError: JSON.parse: end of data after property value in object
SyntaxError: JSON.parse: expected 
SyntaxError: JSON.parse: expected 
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,}');


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}");


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}');



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


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

  • JSON
  • JSON.parse()
  • JSON.stringify()


JavaScript

  • TypeError: invalid ‘instanceof’ operand ‘x’

    The JavaScript exception «invalid ‘instanceof’ operand» occurs when right-hand side operands operator isn’t used with constructor object, i.e.

  • TypeError: ‘x’ is not iterable

    The JavaScript exception «is not iterable» occurs when value which given right-hand side of for…of, argument function such Promise.all TypedArray.from,

  • SyntaxError: Malformed formal parameter

    The JavaScript exception «malformed formal parameter» occurs when argument list of Function() constructor call invalid somehow.

  • URIError: malformed URI sequence

    The JavaScript exception «malformed URI sequence» occurs when encoding decoding wasn’t successful.

i just switched to a mac today and i noticed the JSON.parse that works on other browsers, throws this error on safari.

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

This is the JSON response from my PHP code

   {"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"]"}

This is my Javascript code

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

Please help

UPDATE

I have updated my PHP to echo this

{"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"]}

It works on chrome, safari still throwing this error

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

Console.log(JSON.parse(res)) shows this on chrome

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

Find the answer in similar questions on our website.

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

Понравилась статья? Поделить с друзьями:
  • Error json decode stream url
  • Error jpeglib h not found
  • Error joining network cannot connect to zerotier service
  • Error joining multiplayer session civilization
  • Error java lang verifyerror bad type on operand stack код завершения 1