SyntaxError: “[object Object]” is not valid JSON: usually happens when the value being passed to JSON.parse is not a string value.
Let’s see how we can fix it.
Scenario 1: The value is already an object
Since the value being passed to JSON.parse is already an object, we don’t need to parse it again. It can simply be a definition of the object.
Scenario 2: The object needs to be converted to a string using
There might be cases where we want to parse an object value. In those cases, to avoid the ‘SyntaxError: “[object Object]” is not valid JSON’ error, we need to convert the object to a string first.
The above example is very naive and should not be used. But it can be helpful if there is something else that is happening in between the conversion, like converting the object to a string to store it in local storage and then retrieving it later.
Troubleshooting other scenarios
If you are still stuck, you might want to check the type of variable being passed to JSON.parse:
This will also help you if you forgot to wait for a promise to be resolved when fetching JSON from third-party sources.
If we check the type of jsonData:
We can identify the issue and add a promise.then or an await to fix it.
If the value being passed is a string and we still are getting an error, the string might not be a valid JSON:
In this case, you need to fix the string being passed into the JSON.parse method. You can use a JSON validator like this one to check if the JSON is valid or not.