DEV Community

kb7822836-hash
kb7822836-hash

Posted on

Unexpected token o in JSON at position 1: why it happens and how to fix it

If you have ever seen Unexpected token o in JSON at position 1 (or "[object Object]" is not valid JSON in newer browsers), you are almost certainly calling JSON.parse() on something that is already an object.

Why it happens

JSON.parse() only accepts text. If you pass an object, JavaScript first converts it to the string [object Object]. The parser reads [ as the start of an array, then hits the letter o at position 1 and fails.

const user = { name: "Ali" };
JSON.parse(user); // SyntaxError
Enter fullscreen mode Exit fullscreen mode

The fix is simple: the value is already an object, so use it directly.

console.log(user.name); // "Ali"
Enter fullscreen mode Exit fullscreen mode

The three most common causes

1. Parsing the result of response.json()

response.json() already parses the body and returns an object.

const res = await fetch("/api/user");
const data = await res.json();   // already an object
console.log(data.name);          // no JSON.parse needed
Enter fullscreen mode Exit fullscreen mode

2. Axios and jQuery parse automatically

Axios puts the parsed body in response.data. jQuery with dataType: "json" also passes an object to the callback. Parsing it again causes this error.

3. Saving an object to localStorage without stringifying

localStorage stores strings only. Saving an object directly stores the text [object Object], and that can never be parsed back.

localStorage.setItem("user", JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem("user"));
Enter fullscreen mode Exit fullscreen mode

If the bad value is already saved, remove it once with localStorage.removeItem("user") and save it again.

A quick way to check what you have

console.log(typeof value);   // "object" means do not parse it
console.log(String(value));  // "[object Object]" confirms this error
Enter fullscreen mode Exit fullscreen mode

If the value is a real string that contains broken JSON, a formatter or repair tool helps. I built a free JSON Repair tool that runs in your browser, so nothing you paste is uploaded.

Full guide

I wrote a longer version with the Firefox wording, more examples and an FAQ here: Unexpected token o in JSON at position 1.

Related: Unexpected end of JSON input and Unexpected token < in JSON.

Top comments (0)