Json error что это за ошибка как исправить

Содержание

  1. Обработка ошибок в формате JSON со Spring Boot
  2. Ошибки в JavaScript и как их исправить
  3. Как читать ошибки?
  4. Uncaught TypeError: undefined is not a function
  5. Uncaught ReferenceError: Invalid left-hand side in assignment
  6. Uncaught TypeError: Converting circular structure to JSON
  7. Unexpected token ;
  8. Uncaught SyntaxError: Unexpected token ILLEGAL
  9. Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined
  10. Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined
  11. Uncaught RangeError: Maximum call stack size exceeded
  12. Uncaught URIError: URI malformed
  13. XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource
  14. InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
  15. Заключение
  16. Error decoding JSON data syntax error
  17. Error decoding JSON data syntax error Joomla 3
  18. JSON decode error
  19. json_last_error — Возвращает последнюю ошибку
  20. Описание
  21. Список параметров
  22. Возвращаемые значения
  23. Примеры
  24. Смотрите также

Обработка ошибок в формате JSON со Spring Boot

Часто при работе с микросервисами, построенными с помощью технологии Spring Boot, можно видеть стандартный вывод ошибок подобный этому:

Такой вывод может быть излишним и ненужным клиентам вашего сервиса. Если вы хотите упростить жизнь сторонним сервисам в случае ошибки, то как раз об этом и пойдет речь в данном посте.

Начнем мы с построения небольшого сервиса с одним контроллером. Наш сервис будет принимать запрос на получение пользователя и в случае успеха отдавать данные по пользователю. В случае провала к нам возвращается ошибка. Начнем с простого и далее в статье будем усовершенствовать проект.

Итак, первое, что нам понадобится, это пользователь:

Здесь я использовал библиотеку lombok. Аннотация Data подставляет геттеры и сеттеры в класс. Остальные аннотации добавляют пустой конструктор и конструктор с параметрами. Если вы хотите повторить данный пример у себя в IntelliJ Idea, то вам необходимо поставить галочку в пункте enable annotation processing, либо написать все руками.

Далее нам понадобится сервис (для краткости репозиторий создавать не будем):

Ну и, конечно, сам контроллер:

Итак, у нас есть почти полноценный сервис с пользователями. Запускаем его и смотрим.

При запросе на URL localhost:8080/user/1 нам возвращается json в таком формате:

Все отлично. Но что будет, если сделать запрос на URL localhost:8080/user/4 (у нас всего 3 пользователя)? Правильный ответ: мы получим статус 200 и ничего в ответе. Ситуация не особо приятная. Ошибки нет, но и запрашиваемого объекта тоже нет.

Давайте улучшим наш сервис и добавим в него выбрасывание ошибки в случае неудачи. Для начала создадим исключение:

Теперь добавим пробрасывание ошибки в сервис:

Сделаем перезапуск сервиса и снова посмотрим, что будет при запросе несуществующего пользователя:

Это уже лучше. Гораздо более информативно и код статуса не 200. Такую ситуацию клиент на своей стороне уже сможет успешно и легко обработать. Но, как говорится, есть один нюанс. Ошибки могут быть совершенно разными, и клиенту нашего сервиса придется ставить кучу условных операторов и исследовать, что у нас пошло не так и как это можно поправить. Получается немного грубо с нашей стороны.

Как раз для таких случаев и была придумана аннотация ResponseStatus. Подставим ее на место нашего исключения и на практике посмотрим, как это работает:

Повторим запрос и посмотрим результат:

Отлично! Код статуса и сообщение поменялись. Теперь клиент сможет определись по коду ответа причину ошибки и даже уточнить ее по полю message. Но все же есть проблема. Большинство полей клиенту могут быть просто не нужны. Например, код ответа как отдельное поле может быть излишним, поскольку мы его и так получаем с кодом ответа. С этим нужно что-то делать.

К счастью, со spring boot сделать последний шаг к нашему успешному оповещению об ошибке не так сложно.

Все, что для этого требуется, разобрать пару аннотаций и один класс:

  • Аннотация ExceptionHandler. Используется для обработки собственных и каких-то специфичных исключений. Далее в примере будет понятно, что это значит. На всякий случай ссылка на документацию.
  • Аннотация ControllerAdvice. Данная аннотация дает «совет» группе констроллеров по определенным событиям. В нашем случае — это обработка ошибок. По умолчанию применяется ко всем контроллерам, но в параметрах можно указать отпределенную группу. Подбронее тут.
  • Класс ResponseEntityExceptionHandler. Данный класс занимается обработкой ошибок. У него куча методов, название которых построенно по принципу handle + название исключения. Если мы хотим обработать какое-то базовое исключение, то наследуемся от этого класса и переопределяем нужный метод.

Давайте теперь посмотрим, как все это обЪединить и построить наше уникальное и неповторимое сообщение об ошибке:

Сделаем все тот же запрос и увидим статус ответа 404 и наше сообщение с единственным полем:

Аннотацию ResponseStatus над нашим исключением можно смело убирать.

В итоге у нас получилось приложение, в котором обработка ошибок настраивается максимально гибко и просто. Полный проект можно найти в репозитории github. Надеюсь, что все было просто и понятно. Спасибо за внимание и пишите комментарии! Буду рад вашим замечаниям и уточнениям!

Источник

Ошибки в JavaScript и как их исправить

JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!

Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.

Как читать ошибки?

Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.

Типичная ошибка из Chrome выглядит так:

Структура ошибки следующая:

  1. Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch , а TypeError — это название ошибки.
  2. undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.

Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.

Теперь к самим ошибкам.

Uncaught TypeError: undefined is not a function

Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:

Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.

Несуществующие свойства объекта по-умолчанию имеют значение undefined , что приводит к этой ошибке.

Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.

Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.

Uncaught ReferenceError: Invalid left-hand side in assignment

Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.

Наиболее частый пример этой ошибки — это условие в if:

В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.

Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this .

Uncaught TypeError: Converting circular structure to JSON

Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify .

Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.

Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.

Unexpected token ;

Связанные ошибки: Expected ), missing ) after argument list

Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.

Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected <” или что-то еще.

Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.

Ошибка с [ ] < >( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.

Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.

Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.

Uncaught SyntaxError: Unexpected token ILLEGAL

Связанные ошибки: Unterminated String Literal, Invalid Line Terminator

В строковом литерале пропущена закрывающая кавычка.

Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.

Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

Попытка прочитать null или undefined так, как будто это объект. Например:

Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.

Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

Попытка записать null или undefined так, как будто это объект. Например:

Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.

Uncaught RangeError: Maximum call stack size exceeded

Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.

Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.

Uncaught URIError: URI malformed

Связанные ошибки: URIError: malformed URI sequence

Вызвано некорректным вызовом decodeURIComponent .

Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.

XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url

Эта проблема всегда связана с использованием XMLHttpRequest.

Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Связанные ошибки: InvalidStateError, DOMException code 11

Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.

В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open .

Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open ).

Заключение

JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.

Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.

Источник

Error decoding JSON data syntax error

В этой статье приведу решение проблемы, при которой на вашем сайте возникает ошибка Error decoding JSON data: Syntax error.

Error decoding JSON data syntax error Joomla 3

Данная ошибка может возникнуть при установке модулей, компонентов, плагинов, а также при обновлении сайта Joomla. Как правило, обнаружить ее можно сразу же после установки — сайт не открывается.

По всей видимости, обновление сайта прошло некорректно либо плагин или компонент несовместим с версией движка. Все же в большей степени это касается плагинов, так как именно они являются наиболее частой причиной подобных проблем. Для того, чтобы исправить ошибку, необходимо проверить базу данных на наличие ошибок.

Сделать это можно быстро и очень просто, благодаря скрипту JSON Database Check, который проверит базу данных и покажет в каких таблицах присутствуют ошибки. Перед использованием скрипта обязательно сохраните резервную копию базы данных.

Но скорее всего, если ошибка появилась после установки какого-либо плагина, запись о нем, даже после его удаления через Менеджер расширений, сохранилась в базе данных.

В этом случае можно обойтись и без скрипта. Достаточно проверить БД самостоятельно, установленные расширения (модули, плагины и т.д.).

JSON decode error

Что касается самой проблемы и как можно исправить ее вручную, используя скрипт JSON Database Check. На самом деле он ничего не исправляет, но показывает в каких таблицах и каких именно строках присутствуют ошибки, неверные значения.

Так, распространенной причиной является даже не само значение в строке, а отсутствие, например, закрывающих символов «кавычек«. Все значения должны быть закрыты кавычками

Источник

json_last_error — Возвращает последнюю ошибку

(PHP 5 >= 5.3.0, PHP 7)

json_last_error — Возвращает последнюю ошибку

Описание

Если при последнем JSON кодировании/декодировании возникла ошибка, то возвращает её код.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает целочисленное значение, которое может быть одной из следующих констант:

Коды ошибок JSON

Константа Значение Доступность
JSON_ERROR_NONE Ошибок нет
JSON_ERROR_DEPTH Достигнута максимальная глубина стека
JSON_ERROR_STATE_MISMATCH Неверный или не корректный JSON
JSON_ERROR_CTRL_CHAR Ошибка управляющего символа, возможно неверная кодировка
JSON_ERROR_SYNTAX Синтаксическая ошибка
JSON_ERROR_UTF8 Некорректные символы UTF-8, возможно неверная кодировка PHP 5.3.3
JSON_ERROR_RECURSION Одна или несколько зацикленных ссылок в кодируемом значении PHP 5.5.0
JSON_ERROR_INF_OR_NAN Одно или несколько значений NAN или INF в кодируемом значении PHP 5.5.0
JSON_ERROR_UNSUPPORTED_TYPE Передано значение с неподдерживаемым типом PHP 5.5.0

Примеры

Пример #1 Пример использования json_last_error()

// Неверная json-строка, которая вызовет синтаксическую ошибку,
// здесь в качестве кавычек мы используем ‘ вместо »
$json [] = «<‘Organization’: ‘PHP Documentation Team’>» ;

foreach ( $json as $string ) <
echo ‘Декодируем: ‘ . $string ;
json_decode ( $string );

switch ( json_last_error ()) <
case JSON_ERROR_NONE :
echo ‘ — Ошибок нет’ ;
break;
case JSON_ERROR_DEPTH :
echo ‘ — Достигнута максимальная глубина стека’ ;
break;
case JSON_ERROR_STATE_MISMATCH :
echo ‘ — Некорректные разряды или не совпадение режимов’ ;
break;
case JSON_ERROR_CTRL_CHAR :
echo ‘ — Некорректный управляющий символ’ ;
break;
case JSON_ERROR_SYNTAX :
echo ‘ — Синтаксическая ошибка, не корректный JSON’ ;
break;
case JSON_ERROR_UTF8 :
echo ‘ — Некорректные символы UTF-8, возможно неверная кодировка’ ;
break;
default:
echo ‘ — Неизвестная ошибка’ ;
break;
>

Результат выполнения данного примера:

Пример #2 Совместное использование json_last_error() и json_encode()

// Некорректная последователньость UTF8
$text = «xB1x31» ;

$json = json_encode ( $text );
$error = json_last_error ();

var_dump ( $json , $error === JSON_ERROR_UTF8 );
?>

Результат выполнения данного примера:

Смотрите также

  • json_last_error_msg() — Returns the error string of the last json_encode() or json_decode() call
  • json_decode() — Декодирует JSON строку
  • json_encode() — Возвращает JSON-представление данных

Источник

Are you trying to fix the invalid JSON error in WordPress?

This error appears when editing WordPress posts or pages on your website. You will see a message saying, ‘The response is not a valid JSON response’, and updating that page will fail.

In this article, we will show you how to easily fix the invalid JSON error in WordPress. We will also talk about why this error occurs and how to avoid it in the future.

JSON response is not valid error in WordPress

What Causes the ‘Not a Valid JSON Response’ Error in WordPress?

Failure to receive an expected response from the server causes the ‘Not a valid JSON response’ error in WordPress.

Basically, WordPress needs to communicate with the server while you are editing a blog post. It relies on getting responses from the web hosting server in the background. This response is usually in JSON format, which is used to quickly transport data using JavaScript.

If, for some reason, WordPress fails to get the response, or the response is not in JSON format, then you will see the ‘Not a valid JSON response’ error.

Not valid JSON response error displayed in WordPress

This error could appear for a number of reasons. However, the most likely cause of it is incorrect URL settings in WordPress or broken permalinks.

That being said, let’s take a look at how to easily fix the invalid JSON error in WordPress.

Important: Please make a complete WordPress backup before making any big changes to your website. This allows you to easily restore your website to its previous state.

1. Check WordPress URLs in Settings

First, you need to make sure that your WordPress Address and Site Address settings are correct.

Simply go to Settings » General page. From here, you need to review the ‘WordPress Address (URL)’ and ‘Site Address (URL)’ fields.

WordPress URL settings

For most websites, this setting must have the same URL in both fields.

However, rarely, some users may have given WordPress its own directory and serve the website on a different address. In that case, they can have different URLs here.

However, if your Site Address is incorrect, then that will trigger the invalid JSON error in WordPress.

If you made any changes to the settings, then don’t forget to click on the ‘Save Changes’ button. You can now edit a blog post and see if adding any new blocks or saving that post triggers the ‘Not valid JSON response’ error.

If you are still seeing the error, then continue reading.

2. Fix WordPress Permalink Structure

WordPress comes with SEO friendly URL structure that allows you to use human-readable URLs for your posts and pages.

However, sometimes a user may mess up the permalink settings. This would make it impossible for the WordPress editor to get a valid JSON response and cause the error to appear.

To fix this, you need to simply visit the Settings » Permalinks page. From here, you must carefully review the permalink options.

Fix permalinks in WordPress

If you are unsure whether you are using the right settings, then simply select one of the default formats.

After that, go ahead and click on the ‘Save Changes’ button to store your settings.

You can now try editing a blog post or page to see if the error has disappeared. If it hasn’t, then you can try this next step.

3. Regenerate WordPress .htaccess File

The .htaccess file in WordPress is used as a configuration file to manage SEO-friendly URLs (permalinks).

Normally, WordPress can automatically regenerate and update the file. You can also trigger that update by simply clicking on the ‘Save Changes’ button at the bottom of Settings » Permalinks page.

However, sometimes it may not get updated or has incorrect settings. This will affect your WordPress permalinks and may also cause an invalid JSON response error.

To fix this, you will need to connect to your website using an FTP client or the file manager app in your WordPress hosting account dashboard.

Once connected, you need to locate the .htaccess file in the root folder of your website and download it as a backup to your computer.

Download .htaccess file as a backup

Tip: Can’t locate the .htaccess file? See this quick article on how to find .htaccess file.

After that, you need to edit the .htaccess file using an FTP client or the file manager app.

Edit .htaccess file

Once the file opens, you need to delete all the code inside it and replace it with the following code:

# BEGIN WordPress

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

Don’t forget to save your changes and upload the file back to your website.

You can now visit your website and edit and post or page to see if you can reproduce the invalid JSON response error.

If you are still seeing the error, then there are a few more steps you can take.

4. View the REST API Debug Log

The invalid JSON response error can also mean that WordPress REST API on your website encountered an error.

The REST API is the set of techniques WordPress uses to communicate with the server as you work on your website.

You can see details of this error in the WordPress Site Health tool. Visit the Tools » Site Health page.

REST API issue in WordPress

From here, you may see an issue labeled ‘The REST API encountered an unexpected result’.

Clicking on it will show you more details, which may give you some clues about which plugin or third-party service is causing the issue.

If this doesn’t provide any clues, then you can move on to the next step.

5. Deactivate All WordPress Plugins

Occasionally, WordPress plugins may conflict with each other or the WordPress core software. This can result in unexpected behavior and could be a potential reason for the invalid JSON error.

Simply go to the Plugins » Installed Plugins page. From here, select all your WordPress plugins and then choose ‘Deactivate’ from the ‘Bulk Actions’ drop-down menu. Now, click the ‘Apply’ button to continue.

Deactivate all plugins

WordPress will now deactivate all your installed plugins.

You can now try again to reproduce the error. If the error disappears, then this means one of the plugins installed on your website was causing it.

To figure out which plugin is the problem, you just need to activate them one by one and try to reproduce the error. Repeat this until you find the culprit.

After that, you can reach out to the plugin author for support or find an alternative plugin.

6. Temporarily Switch to the Classic Editor

If all the above steps fail, then you can temporarily switch to the Classic Editor for WordPress.

This older version of the WordPress editor uses a simpler text editor and doesn’t rely heavily on REST API to get JSON responses.

To use it, you need to install and activate the Classic Editor plugin. For more details, see our step-by-step guide on how to install a WordPress plugin.

The plugin works out of the box, and it will disable the Gutenberg editor upon activation.

You can now continue working on your website and get back to troubleshooting later.

7. Further Troubleshooting

A number of things can block WordPress REST API or make it return an invalid JSON response. We have addressed the most likely culprits above, but if that didn’t fix it for you, then here are some more steps that you can try.

Switching to a Default WordPress Theme

Sometimes a conflict between your WordPress theme and a plugin or the WordPress core may result in unexpected behavior.

You can test this, by simply switching to a default WordPress theme like TwentyTwentyOne or Twenty-TwentyTwo.

Temporarily Turn Off Website Application Firewall

If you are using a WordPress firewall like Sucuri, Cloudflare, or a plugin, then it may sometimes block legitimate requests too.

The easiest way to figure this out is by temporarily disabling your WordPress firewall plugin or service.

Some application-level WordPress firewalls can be disabled by simply deactivating the plugin. For DNS-level firewalls like Sucuri and Cloudflare, you can disable them from your account dashboard.

Turn On Debugging in WordPress

WordPress comes with a built-in feature that allows you to keep a log of errors. However, it is not enabled by default.

To turn it on, you need to add the following code to your wp-config.php file:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

After that, WordPress will keep a log of all errors in a debug.log file located inside the /wp-content/ folder. You can access this file by using an FTP client.

The error log may provide you with a clue about what may be causing the invalid JSON error on your website. For more details, see our guide on setting up WordPress error logs and using them for debugging errors.

Seek Expert Help

Finally, if all else fails, then this could be due to a misconfiguration on your WordPress hosting server. Most reliable WordPress hosting companies are able to help users with common WordPress issues.

Simply reach out to them via live chat or support ticket, and they may be able to help you fix it.

We hope this article helped you learn how to fix the invalid JSON error in WordPress. You may also want to see our complete handbook of the most common WordPress errors and how to fix them, along with our top picks for the best email marketing services for small business.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience building WordPress websites. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.

JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.

Why do we get JSON parse error?

Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true

How to handle JSON parse error?

There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.

1. Using try-catch block

The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

try {
  const json = '{"result":true, "count":42}';
  const obj = JSON.parse(json);
  console.log(obj.count);
  // expected output: 42
  console.log(obj.result);
  // expected output: true
} catch (e) {
  console.log(e);
  // expected output: SyntaxError: Unexpected token o in JSON at position 1
}

2. Using if-else block

Another way to handle JSON parse error is using if-else block.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
if (obj instanceof SyntaxError) {
  console.log(obj);
  // expected output: SyntaxError: Unexpected token o in JSON at position 1
} else {
  console.log(obj.count);
  // expected output: 42
  console.log(obj.result);
  // expected output: true
}

3. Using try-catch block with JSON.parse()

The third way to handle JSON parse error is using try-catch block with JSON.parse().

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
  try {
    return JSON.parse(value);
  } catch (e) {
    return value;
  }
});
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true

4. Using try-catch block with JSON.parse() and JSON.stringify()

The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
  try {
    return JSON.parse(value);
  } catch (e) {
    return value;
  }
});
const str = JSON.stringify(obj);
console.log(str);
// expected output: {"result":true,"count":42}

Проблема, 479775bb7226b040aad141e3319f2aad-full.png что означает эта ошибка JSON?Как ее исправить?


  • Вопрос задан

    более трёх лет назад

  • 4904 просмотра



33

комментария

Пригласить эксперта


Ответы на вопрос 1

Rsa97

Rsa97

@Rsa97

Для правильного вопроса надо знать половину ответа

Ошибка – пустая строка после завершения PHP-блока. Всё, что не находится внутри <?php ?> выводится как есть.
Самое лучшее решение – убрать завершающую скобку ?>.


Похожие вопросы


  • Показать ещё
    Загружается…

16 мая 2023, в 13:10

500 руб./в час

16 мая 2023, в 12:46

45000 руб./за проект

16 мая 2023, в 12:37

300 руб./в час

Минуточку внимания

Were you trying to upload a file or edit a piece of content on your WordPress site only to be met by a scary red message saying something like, “Updating failed. The response is not a valid JSON response?”

Wordpress developer troubleshooting the invalid JSON response error

The WordPress invalid JSON response error happens in the new Block Editor (AKA Gutenberg) when something goes wrong on your site. Because it appears when you’re working on content, it can be a frustrating error because it can get in the way of whatever task you’re trying to accomplish.

Thankfully, there are some straightforward steps that you can take to fix this problem and get your site working properly again.

In this post, we’ll briefly explain what the invalid JSON response error means. Then, we’ll share a number of troubleshooting steps you can implement to fix the problem.Grow Your Business With HubSpot's Tools for WordPress Websites

If you see “Updating failed. The response is not a valid JSON response,” it will typically appear when you’re working on content in the WordPress Block Editor. In some cases, it can also appear when you’re trying to upload a media file to your site, especially if you’re trying to upload the file directly to a block in the Block Editor.

So, why does it happen?

When you’re working in the Block Editor, the editor is in constant communication with your WordPress site’s server. This “communication” happens behind the scenes, but it’s important to the editor.

One of the “languages” of this communication is JSON, short for JavaScript Object Notation. If something goes wrong with this communication, WordPress will show the “The response is not a valid JSON response” message. It means that the editor failed to get a response to the server or the response wasn’t in a valid JSON format.

Basically, if the editor can’t communicate with the server, it will show this error message instead.

To fix the problem, you essentially need to fix whatever is getting in the way of the communication.

How to Fix the WordPress Invalid JSON Response Error

Now that you know what the JSON response error message means, let’s dig into some troubleshooting steps to fix this problem.

We’ll try to put these in a logical order, so that the first troubleshooting steps are the most likely to fix the problem.

For that reason, we recommend trying these processes in the order that we’ve written them.

Fix your site’s permalinks and .htaccess file.

One of the most common causes of the invalid JSON response error is an issue with your site’s .htaccess file and/or WordPress permalinks.

Thankfully, this is also one of the simplest debugging steps. Here’s all you need to do:

  1. Go to Settings → Permalinks in your WordPress dashboard.
  2. Verify that the correct permalink structure is selected — If the correct structure is already selected, you don’t need to change anything.
  3. Click the Save Changes button. Even if you didn’t change anything, you should still click the save changes button because it will force WordPress to regenerate its rewrite rules.

WordPress JSON error fix

Now, go back to the editor and see if that fixed the invalid JSON response error.

If you’re still experiencing issues, you can guarantee that your .htaccess file is clean by deleting it and forcing WordPress to generate a new one. Here’s how:

  1. Connect to your server using an FTP client or cPanel File Manager.
  2. Find your .htaccess file (it should be in the root folder).
  3. Download a copy of the file to your computer as a backup (just in case).
  4. Delete the file from your server.
  5. Go to Settings → Permalinks in your WordPress dashboard and click Save Changes. This will force WordPress to generate a new, clean .htaccess file.
  6. Check if the problem is fixed.

Finally, there’s one last potential fix, but it really only applies to advanced WordPress users.

If you’re working in a local development environment via a tool such as XAMPP, you’ll also want to make sure that you’ve properly configured the .htaccess file permissions and enabled mod_rewrite in Apache’s settings. Make sure to restart Apache once you’ve made the changes.

Check your WordPress site URL.

Another common cause of the invalid JSON response error is a problem with your WordPress site URLs.

The problem can arise if your site URLs aren’t correct or if you accidentally put HTTP instead of HTTPS (assuming your site is using an SSL certificate).

To fix this problem, go to Settings → General in your WordPress dashboard.

You’ll want to verify two things here:

  1. Make sure that the URLs are correct. On the vast majority of WordPress sites, your WordPress Address and Site Address should be the same.
  2. Make sure that both URLs start with https if you’re using an SSL certificate on your site.

Then, save your changes.

WordPress JSON error resolution

In very rare cases, your site’s URLs might have been hard-coded into your wp-config.php file. If this is so, any changes that you make via your WordPress dashboard won’t apply because those hard-coded changes will override the dashboard settings.

Again, this is very rare because you need to manually add those hard-coded changes, but it can happen so it might be worth checking. For example, your WordPress developer might have done this for you without letting you know.

Here’s how to check if this is the case:

  1. Connect to your site’s server using FTP or cPanel File Manager.
  2. Edit the wp-config.php file.
  3. Search for define( ‘WP_HOME’ OR define( ‘WP_SITEURL’

Here’s an example of what it might look like:

JSON error example

If you do find these code snippets, you can either:

  1. Verify that both site URLs are correct and leave the code snippets in your wp-config.php file.
  2. Remove the code snippets, which will tell your site to use the URLs that you set in your WordPress dashboard.

Check for a mixed content warning (HTTPS issue).

If your site is using an SSL certificate (which most sites do nowadays), issues with mixed HTTP and HTTPS content can trigger the invalid JSON response error.

In order for your website to benefit from the security of your SSL certificate, you need to use HTTPS to load every resource on your site. If you still have some resources loading over HTTP, this can trigger something called a mixed content warning and which causes problems with the invalid JSON response error.

In the previous section, you made sure that your WordPress site URLs both start with HTTPS (if you’re using an SSL certificate), which should fix many problems with mixed content already.

However, there could still be issues, especially if you’re using a plugin to handle migrating an older site from HTTP to HTTPS.

If you’re using a plugin, make sure that you’ve fully enabled its mixed content fixer features. You can do this by going to Settings → SSL and enabling both the Mixed content fixer and the Fire mixed content fixer with different method toggles:

JSON error plugin fix

If you’re not using an SSL plugin, many hosts now offer tools to force HTTPS, which you can find in your hosting dashboard or by consulting your host’s documentation.

Finally, if you’re using Cloudflare on your site, make sure that you’ve set its Encryption Mode to Full (Strict) or Full. Try the Strict option first and then switch to just Full if you experience any issues.

Disable your security firewall.

If you use a firewall to protect your WordPress site, this can sometimes interfere with the editor’s connection to your server and trigger the invalid JSON response error.

This is especially common with ModSecurity rules from your web host, though it also might be triggered by popular security plugins.

To troubleshoot this, try deactivating your firewall or security plugin and see if that fixes the problem. If the editor starts working, you know that something is going wrong with your firewall.

Of course, leaving the firewall disabled isn’t a viable long-term strategy, but you at least now know what’s causing the problem and you can start fixing things.

If your firewall is implemented at the hosting level, you can ask your WordPress host to investigate and whitelist the editor to avoid having it trigger the firewall. That way, you can maintain the protection of your site’s firewall while still avoiding the invalid JSON response error.

If you’re using a WordPress security or firewall plugin, you have two options:

  1. You can replace your existing firewall plugin with a different plugin that protects your site without causing problems.
  2. You can reach out to the plugin’s developer to ask them about whitelisting to avoid future problems.

If you’re using Wordfence (or another plugin that has a “learning mode”), you can also try reactivating learning mode to reset its firewall rules.

Use a classic editor plugin.

Some people report being able to fix the invalid JSON response error by activating and deactivating the Classic Editor (WordPress’ old, TinyMCE-based editor).

It only takes a couple of minutes, so it’s worth seeing if this trick can fix your problems.

Here’s all you need to do:

  1. Install the official Classic Editor plugin from WordPress.org.
  2. Go to Settings → Writing and use the drop-down to select the Classic Editor as the default editor for all users.
  3. Save your changes.
  4. Use the same drop-down to change the default editor back to the Block Editor.
  5. Save your changes again.

Classic editor JSON error

Now, try creating or editing a new post and see if it works.

Deactivate your WordPress plugins.

Debugging WordPress errors can be tricky because the plugins that you’re using introduce a lot of variables to the equation. With 58,000+ plugins at WordPress.org, that’s a lot of edge cases that could be triggering the invalid JSON response error.

One easy way to figure out if a plugin is causing the problem is to deactivate all of your plugins.

If you’re still seeing the invalid JSON response error after deactivating everything, you can be confident that it’s not an issue with your plugins and you can reactivate them.

On the other hand, if the error goes away after deactivating your plugins, you know that there’s a problem with one of the plugins that you’re using.

To find the problematic plugin, you can reactivate your plugins one by one, making sure to test the editor after each plugin. If you activate a plugin and see the error appear right after that, you’ve found the issue.

From there, you can either replace that plugin with an alternative that doesn’t cause a problem or you can reach out to the plugin’s developer for help and a potential fix.

Upload media files via the Media Library.

If you’re seeing the “The response is not a valid JSON response” when you try to upload media files via the Block Editor, one fix is to upload these images directly to your Media Library instead of via the block interface.

When you add an image block (or the block for another type of media file), click on the Media Library option and upload files that way instead of just clicking the Upload button.

When you do that, you’ll see the regular WordPress Media Library uploader interface, which should let you bypass the invalid JSON response error.

JSON error wordpress

Check the console and debug log.

For more advanced users, you can try digging into your browser’s console or various debug logs to find a more specific problem. This isn’t really a solution for casual users, though, as you’ll need some technical knowledge to accomplish anything here.

First off, you can use the Network tab in Chrome Developer Tools to find issues with Ajax calls.

In the Network tool, select FETCH/XHR to filter out Ajax calls and debug issues with the REST API.

JSON error Debug log

You can also view some REST API issues from your WordPress dashboard. Go to Tools → Site Health and look for a heading such as “The REST API encountered an unexpected result”.

Use the Classic Editor as a short-term fix.

This last method isn’t a permanent fix, but it is a workaround that can help you publish content in a pinch.

Earlier, we told you about the Classic Editor trick where you switch your site to the Classic Editor but then switch back to the Block Editor.

Well, if none of the other tips have worked for you, one way to continue publishing content is to just leave the Classic Editor enabled and use that to create content for the time being.

This isn’t an actual “fix” because you’ll lose all of the functionality that the Block Editor adds. However, it will give you the ability to work on content while you continue debugging the “The response is not a valid JSON response” message.

Additionally, once you get the Block Editor working again, you’ll be able to convert your Classic Editor content into blocks with just a few clicks.

Fixing the WordPress Invalid JSON Response Error

Seeing a “Updating failed. The response is not a valid JSON response” message can be frustrating because it appears while you’re trying to work in the WordPress editor.

Thankfully, for most sites, debugging this error shouldn’t be too painful.

In most situations, simply re-saving your WordPress permalinks should fix the problem. If that doesn’t work, you might need to dig into other fixes such as checking your site URLs, fixing mixed content warnings with HTTPS, adjusting your firewall, and more. Implement these troubleshooting steps and you should have your site functioning properly again in no time.Use HubSpot tools on your WordPress website and connect the two platforms  without dealing with code. Click here to learn more.

Добавить комментарий