2 Solutions for Unexpected token "u" in JSON at position 0

Bits Lovers
Written by Bits Lovers on
2 Solutions for Unexpected token

JavaScript is one of the three core technologies of the web, alongside HTML and CSS. It lets you add animation, react to user actions, and update content without page reloads.

The Unexpected token “u” in JSON at position 0 error shows up when you try to parse an undefined value with $.parseJSON or JSON.parse. The fix: check what value you’re passing in and make sure it’s valid JSON before parsing.

The error mentions “u” and position 0, which tells you the first character in the string is “u” - the first letter of “undefined”. Since “undefined” isn’t valid JSON, the parser chokes on it.

What does “undefined” mean in JavaScript?

In JavaScript, “undefined” means a variable has been declared but hasn’t been assigned anything yet. When you declare let foo; without assigning a value, JavaScript gives it undefined by default.

let foo;
console.log(foo); // logs "undefined"

One thing worth noting: undefined and null aren’t the same. null is an explicit value you assign when you want to represent “no value.” undefined is what JavaScript gives you automatically when you don’t assign anything.

Accessing a property that doesn’t exist also returns undefined:

let obj = {};
console.log(obj.someProp); // logs "undefined"

Error in Developer Tools

Here’s what the error looks like in Chrome:

Uncaught SyntaxError: Unexpected
token u in JSON at position 0
      at JSON.parse ()
      at index.js:62

Debugging

Debugging is part of the job. Chrome’s DevTools is the go-to for inspecting JavaScript running in the browser.

To open DevTools: right-click any element and choose “Inspect,” or press Ctrl+Shift+I (Cmd+Shift+I on macOS).

The “Sources” tab is where you can set breakpoints and step through your code. Click to the left of a line number to pause execution there.

Use the step buttons to walk through code one line at a time. The “Watch” panel lets you monitor specific variables. The console is handy for testing snippets or logging output.

Root Cause

So what causes “Unexpected token u in JSON at position 0”? Three common reasons:

  1. You’re trying to access an attribute on an object that doesn’t exist
  2. You’re pulling data from localStorage or a server response that turned out to be empty or invalid
  3. You’re reading data before the page finished loading (race condition)

The Fix: try-catch

The best approach is wrapping your JSON.parse in a try-catch:


try {
  const obj = JSON.parse(undefined); // Try to convert
} catch (e) {
  // Only runs if parsing fails
  console.log('Message: ', e.message);
}

The try block attempts to parse the value and store it in obj. If the value isn’t valid JSON, JSON.parse throws an exception and the catch block runs instead.

One thing to keep in mind: all JSON values are strings, but JSON has strict syntax rules. A string has to actually be valid JSON to parse correctly.

Before pulling data from your backend, log the response and double-check that it’s actually valid JSON.

Content-Type Header

Check your browser’s DevTools to verify that requests to your server include application/json in the Content-Type header. This header tells the recipient what format the payload is in, so it knows how to parse it.

If the Content-Type is wrong, the recipient might not parse your JSON correctly.

Tip: when you have a large JSON string and you can’t spot the issue, use an online JSON validator. Sometimes a tiny character bug is impossible to see manually.

If things seem stuck, try clearing browser data. I usually open an Incognito window to rule out cache issues.

Local Storage

Local storage lets websites store data in the browser as key-value pairs. It came with HTML5 as an alternative to cookies, and it can hold way more data.

Data in localStorage persists even after you close the browser tab. It’s isolated per domain, so other sites can’t read it.

You can store authentication tokens, user preferences, or anything else you need to keep around.

To clear local storage:

localStorage.clear()

After clearing, if you want to store a non-JSON value, convert it first with JSON.stringify:


// Storing an object
localStorage.setItem('site', JSON.stringify({blog: 'BitsLovers'}));

// Reading it back
const obj = JSON.parse(localStorage.getItem('site'));

Waiting for the Page to Load

If you’re reading data before the page finishes loading, you’ll get this error. Use window.onload or jQuery’s $(document).ready() to wait until everything is ready.

Here’s how:


// Using onload
window.onload = function getUser() {
  fetch('https://app.bitslovers.com/api/')
    .then(response => {
      if (!response.ok)
        throw new Error(`Error message: ${response.status}`);
      return response.json();
    })
    .then(result => {console.log(result);})
    .catch(err => console.log(err));
};

// Using jQuery ready
$(document).ready(function () {
  $.getJSON('https://aps.bitslovers.com/api/', function (resp) {
    console.log(resp);
  });
});


The getUser function waits for the page to load, then uses the Fetch API to get JSON from the URL. If something goes wrong, it throws an error with the status code. The $.getJSON shortcut from jQuery does essentially the same thing with less code.

Conclusion

A few things to check when you hit this error: make sure your data is loaded before you parse it, verify the Content-Type header is set correctly, and confirm your response is actually valid JSON before calling parse.

If you’re dealing with localStorage, remember to stringify objects before storing them and parse them when you pull them back out. For race conditions, window.onload or $(document).ready ensures the page is ready before you start fetching data.

With these checks in place, you should be able to avoid this error in most situations.

Happy coding!

Bits Lovers

Bits Lovers

Professional writer and blogger. Focus on Cloud Computing.

Comments

comments powered by Disqus