Error 0 error decoding json data syntax error

Please do not spread misinformation that the libraries/vendor directory contains broken code in 3.6.3. It doesn't.

Please do not spread misinformation that the libraries/vendor directory contains broken code in 3.6.3. It doesn’t.

The issue that is being run into is that an additional error check was added to the JSON formatter in the Registry API. So specifically what is the common issue here is that data sources which are supposed to contain valid JSON formatted data do not. This added error check looks to see if there was an error converting the string it was given (which is supposed to be valid JSON) into an object readable by the PHP code, and if there was an error with that process it throws an Exception indicating the error.

The common culprit I’m seeing for this is reading data from either the extensions or modules database tables. Both of them have `params` columns which have data stored in JSON format. To hit the line that tries to decode the JSON string to an object, the column has to have either a «{» as its first character or a «}» as its last character. If the column has a null or empty value, it won’t reach this line.

Basically what this is indicating is there is improperly structured data being given into the API to decode and the API hits an error with it (correctly so). What changed between 3.6.2 and 3.6.3 is that the error was silently ignored.

Sorry for the highly technical explanation before this point, but there’s really no other way to get around that.

As for the fact that things work if you restore the 3.6.2 version of this directory, what it was doing there was basically receiving a null or false return value versus the decoded data object. So ultimately the data that the code was looking for isn’t actually getting loaded into memory. Now in a lot of places this really isn’t an issue because the PHP code will use sensible default values when this data doesn’t exist. It does become an issue if you’ve customized parameter values though and will cause your custom values to not be used.

Long and short, restoring the 3.6.2 code «works», but it’s not addressing the underlying issue of invalid data being fed into the code to be processed. How that data got there, I can’t say, I can just diagnose the symptoms.

На днях накатал обновление с 3.6.2 до 3.6.5, и как следствие столкнулся с ошибкой Error decoding JSON data: syntax error В итоге прочитал много разных советов и постов, и часто встречал эту ссылку https://github.com/robwent/joomla-json-db-check Везде писали, просто закинь и запусти, либо давали sql запросы, по типу

UPDATE xxx_extensions SET params="" WHERE params = "{""}";

В общем в помощь другим столкнувшимся с данной бедой, опишу более подробно, что нужно сделать, ибо я нигде этого не нашел, в том числе и в данной ветке форума.
Итак, столкнувшись с этой ошибкой, первым делом загрузите с гитхаба, по ссылке выше скрипт, и спокойно его запускайте, на данном этапе бекап бд не требуется, так как этот скрипт — просто анализирует ключевые таблицы на соответствие json синтаксиса по полям параметров. И в ответ выдает список таблиц и строк содержащих ошибку. Он не лечит, он не указывает, где конкретно будет ошибка. Нет, он только указывает, что она есть. Далее нужно самостоятельно проанализировать, и определить, ошибку и исправить ее. Лично я все делал в HeidiSQL, так в нем мне не приходится тратить время на составление запросов, а можно воспользоваться интерфейсом «поиск — замена» — ошибок было много и все они однотипные.
Пример результата сканирования таблиц, для понимания, на что обращать внимание.:

Здесь мы видим, что таблица joomla_content в строке 1214 содержит поле с ошибкой. И выдано содержимое поля.
С первого взгляда, найти ошибку затруднительно, особенно для тех, кто не имеет представления, о построении содержимого. Потому давайте разберем содержимое. Логично, что здесь мы видим параметр и его значение, к примеру «show_title» — это параметр, а «0» — значение. Их здесь много, и все они пишутся обязательно в кавычках, после параметра следует двоеточие, затем в кавычках значение. Кавычки обязательны, даже если значение пустое. Разделение между собой параметров осуществляется через запятую. Понимая все это, найти ошибку не составит труда, в примере две ошибки:
«link_parent_category»:»,
«show_urls_images_frontend»:»}

Всего-то не хватает второй кавычки. Так как у меня проблемы были с сайтом, в котором бд, переносилась с другого движка, посредством импорта с адаптированного сsv  файла, в момент импорта что-то терялось. Местами, так и вовсе, были задвоенные кавычки — «»link_parent_category»»:»»»».
Думаю принцип поиска и исправления понятен, и кому-то поможет, просто ошибки могут быть у всех разные, и стандартные рекомендации с форуме не помогут. Именно так и было в моем случае, все писали только о модулях, а о том, что ошибки могут оказаться и в таблицах со статьями, никто не предполагал.
Всем удачи в исправлении этой ошибки!

  • Index
  • Recent Topics
  • Search

  • Log in

  1. Forum

  2. K2 Community Forum

  3. English K2 Community

  4. 0 Error decoding JSON data: Syntax Error


6 years 3 months ago #158910
by Zoe

Hello,

I have recently upgraded Joomla! to 3.6.4 and now I get the above error (0 Error decoding JSON data: Syntax Error) on a number of K2 items while on others I don’t.

I have tried resetting the parameters as discussed on issues.joomla.org/tracker/joomla-cms/12460 — I have removed the Editor and JB Library is not installed. I still get the same error.

0 Error decoding JSON data: Syntax error
Call stack
# Function Location
1 JApplicationCms->execute() /[path]/administrator/index.php:51
2 JApplicationAdministrator->doExecute() /[path]/libraries/cms/application/cms.php:261
3 JApplicationAdministrator->dispatch() /[path]/libraries/cms/application/administrator.php:152
4 JComponentHelper::renderComponent() /[path]/libraries/cms/application/administrator.php:98
5 JComponentHelper::executeComponent() /[path]/libraries/cms/component/helper.php:380
6 require_once() /[path]l/libraries/cms/component/helper.php:405
7 JControllerLegacy->execute() /[path]/administrator/components/com_k2/k2.php:147
8 K2ControllerItem->display() /[path]/libraries/legacy/controller/legacy.php:702
9 K2Controller->display() /[path]/administrator/components/com_k2/controllers/item.php:21
10 JControllerLegacy->display() /[path]/administrator/components/com_k2/controllers/controller.php:20
11 K2ViewItem->display() /[path]/libraries/legacy/controller/legacy.php:664
12 JoomlaRegistryRegistry->__construct() /[path]administrator/components/com_k2/views/item/view.html.php:466
13 JoomlaRegistryRegistry->loadString() /[path]/libraries/vendor/joomla/registry/src/Registry.php:72
14 JoomlaRegistryFormatJson->stringToObject() /[path]/libraries/vendor/joomla/registry/src/Registry.php:366

Please help.

Please Log in or Create an account to join the conversation.


6 years 3 months ago #158917
by Krikor Boghossian

Hello,

This is a core Joomla! issue, a lot of sources for this error.
There are several solutions posted online, I think one from Joomlashack was the most thorough.


JoomlaWorks Support Team

Please search the forum before posting a new topic :)

Please Log in or Create an account to join the conversation.


6 years 3 months ago6 years 3 months ago #158929
by Zoe

Hello Krikor,

Thanks for the link to the JoomlaShack topic, I checked it. update [prefix]_modules set params=»» WHERE params = «{«»»}»;
is the first thing I did. I got a return of 0 rows updated.

I saw further down in the Github conversation that it was argued this is not a Joomla core issue and it is an extensions issue to do with the extensions not being able to handle this higher level of error handling, if I’ve understood it correctly.

I have also implemented the #116713 solution and defined the following in the top of my index.php file:

unset($this->_scripts[JURI::root(true).’/components/com_k2/js/k2.js?v2.7.1&sitepath=’.JURI::root(true).’/’]);

And I’m still getting the error. I thought disabling the javascript would resolve the JSON error? Am I wrong?

I have currently resorted to deleting the old K2 items and replacing them with new ones (after copying the content directly out from the SQL) this works but it is far from an ideal solution.

Any ideas?

Last edit: 6 years 3 months ago by Zoe. Reason: updated k2.js version in line of code

Please Log in or Create an account to join the conversation.


6 years 3 months ago #158930
by Krikor Boghossian

The unsetting of a JS script is a frontend issue, it won’t affect any aspect of data stored in the db.

The item’s params are stored in JSON format.
If removing an item solves the issue, then you might have located the culprit.


JoomlaWorks Support Team

Please search the forum before posting a new topic :)

Please Log in or Create an account to join the conversation.


6 years 2 months ago #159082
by Mohamed Abdelaziz

Hello All,

I’ve found this issue while I’m editing some K2 items, after upgrading to Joomla 3.6.4
After some debugging on my personal website, I fixed this issue by hacking the file /administrator/components/com_k2/views/item/view.html.php
I replaced this statement:

FilterOutput::objectHTMLSafe($item, ENT_QUOTES, array(
			'video',
			'params',
			'plugins'
		));

With this one:

FilterOutput::objectHTMLSafe($item, ENT_QUOTES, array(
			'video',
			'params',
			'plugins',
                        'metadata'
		));

You can give it a try, may be it fix your issue.


Multiple Extra Fields Groups for K2
AutoMeta for K2
Chained Fields for K2
More K2 Extensions In My
Extensions Store

Please Log in or Create an account to join the conversation.


6 years 2 months ago #159091
by smarterweb

we had the same issue, but only after importing Joomla articles into K2. Seems there is leftover metadata that creates the problem.
A solution is to clear the column «metadata» in k2 table «k2_items» here’s the sql query:

UPDATE `tableprefix_k2_items` SET `metadata` = »

NOTE: You will of course loose your metadata if there was any.

Please Log in or Create an account to join the conversation.


6 years 2 months ago6 years 2 months ago #159096
by Zoe

I had kept a few non-working articles to test a fix and yours worked.
Where Joomla articles had been imported, the metadata was showing:
{«robots»:»»,»author»:»»,»rights»:»»,»xreference»:….

Where I had recreated articles in K2 after the upgrade, the same metadata was showing:
robots=
author=

Now that I have cleared that field, I can now access the old articles!

Thank you smarterweb!

Last edit: 6 years 2 months ago by Zoe.

Please Log in or Create an account to join the conversation.


6 years 2 months ago #159097
by Zoe

Hello Mohamed, I went looking for the line you quoted and couldn’t find it but it was definitely a problem with the metadata. Thanks!

Please Log in or Create an account to join the conversation.


6 years 2 months ago #159101
by Krikor Boghossian

Hello Mohammed,

Care to make a PR?


JoomlaWorks Support Team

Please search the forum before posting a new topic :)

Please Log in or Create an account to join the conversation.


6 years 2 months ago6 years 2 months ago #159103
by Mohamed Abdelaziz

Hello Krikor,

Yes of course, just wanted to have some more tests from others before the PR.

Can you help in this test?


Multiple Extra Fields Groups for K2
AutoMeta for K2
Chained Fields for K2
More K2 Extensions In My
Extensions Store

Last edit: 6 years 2 months ago by Mohamed Abdelaziz.

Please Log in or Create an account to join the conversation.

  1. Forum

  2. K2 Community Forum

  3. English K2 Community

  4. 0 Error decoding JSON data: Syntax Error

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

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

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

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

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

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

JSON decode error

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

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

1
{"jQuery":"0","show_title":"0","link_title":""}

даже, если значение пустое

Неверный вариант будет выглядеть

1
{"jQuery":"0","show_title":"0","link_title":"}

Ошибкой будет отсутствие «кавычки» после

.

Are you getting into trouble with the message “Error Decoding Json Data: syntax error” on your Joomla backend login? Don’t ignore the article, this blog will share with you a step-by-step guide to tackle this problem.

What caused the error “Error Decoding Json Data: syntax error” on your Joomla website?

If your Joomla is running the 3.6.3 version, it is certain that you will get more error messages if you store the data improperly. In fact, Joomla doesn’t cause the issue, it is only good at reporting errors when you have any incorrect storage.

And “Error Decoding Json Data: syntax error” is also one of the prevalent errors that can be caused due to wrong data. Hence, in order to handle this problem, you need to find and fix the data itself.

However, where is the data? Usually, it is displayed in the “params field in the _extensions table or _modues table. In today’s blog, we will help you fix this error quickly without difficulties. Now, let’s explore.

How to fix the “Error Decoding Json Data: syntax error” issue

Here are all steps you need to perform to fix this error in your database

Step 1: Go to the Cpanel hosting account for this account on your web host. And make sure that you have backed up your database before.

Step 2: After login into Cpanel, let’s go down to the phpMyAdmin option in the Databases section and click on it. You can use the search feature in the top right corner to find this option.

Step 3: After clicking on it, this immediately takes you to a place where all databases belonging to your web hosting account will be displayed. Now, you need to click on the database that runs your Joomla site. Then, there is a table that runs your Joomla website displayed.

Step 4: Next, let’s click on the “SQL ” tab at the top of the page, and then it will show the fields where you can enter a command that can help you fix that error.

Step 5: You need to enter the following command in that field.

update abc_modules set params = ” where params like ‘%{“”}%’;”

Don’t forget to change “abc” to your table prefix in your database. In addition, in order to run the above command on your _extension table too. It is necessary to replace abc_modules with abc_extensions.

Step 6: Click on the “Go” button to finalize the process.

After that, you will notice a message that shows the number of your rows affected, which mean that your issue should be fixed.

Now, you can go to the Administrator backend of your Joomla site and log in again.

Sum up

As we mentioned above, this is a popular issue on your Joomla website. Hopefully, our blog helped you handle the “Error Decoding Json Data: syntax error” problem effectively. In that case, your problem is still not resolved, feel free to mention your difficulties by leaving a comment below. If you find this blog useful, don’t forget to share it with your friends. Further, are you going to make a difference for your Joomla site? If yes, don’t miss a list of beautiful, modern Joomla templates on our website.

  • Author
  • Recent Posts

Lt Digital Team (Content &Amp; Marketing)

Welcome to LT Digital Team, we’re small team with 5 digital content marketers. We make daily blogs for Joomla! and WordPress CMS, support customers and everyone who has issues with these CMSs and solve any issues with blog instruction posts, trusted by over 1.5 million readers worldwide.

Lt Digital Team (Content &Amp; Marketing)


Закрытый форум для вебмастеров


  1. Dmitrijs

    Dmitrijs
    Cкладчик

    Регистрация:
    12 мар 2015
    Сообщения:
    28
    Симпатии:
    2

    Скриншот ошибки : https://gyazo.com/dc6bde674d05f138b447d7219c9313a0

    Максимально подробное описание ошибки : Обновляюсь на Joomla 3.6.3, когда захожу в настройки шаблона, остается только то, что видно на скриншоте. В заголовке вкладки надпись «Error: 0 Error decoding JSON data: Syntax error»
    в консоли «ReferenceError: jQuery is not defined»
    Пробовал обновить на 3.6.4, та же ерунда.
    Нашел в нете кривое решение:
    скачал старое обновление Joomla_3.6.2-Stable-Update_Package.tar.bz2 с https://github.com/joomla/joomla-cms/releases/tag/3.6.2
    заменил все файлы в папке librariesvendor.
    Заработало, но это как-то не решение? при обновлении все равно слетает.
    В quickstart воспроизвести проблему не удалось, там все ок.
    Спасите-помогите.

    Название хостинга или локального сервера : nano.lv

    Версия php : 5.6

    Ссылка на бекап вашего сайта (можно сделать при помощи компонента akeeba backup) :


  2. Artur

    Artur
    Тех. поддержка

    Регистрация:
    25 дек 2015
    Сообщения:
    898
    Симпатии:
    139

    Обновилась Джумла, и опять возникли проблем)
    Ошибки могут возникать с шаблонами или с компонентами, и исправляют их разработчики, выпуская соответствующие фиксы-обновления)

    Быстрое решение, как сказано выше, залить старую версию 3.6.2. поверх новой

    Эта тема активно обсуждается на оф. сайте Joomla.org — https://forum.joomla.org/viewtopic.php?f=706&t=937036

    Возможное решение проблемы

    The error is pulled in the file:
    /libraries/vendor/joomla/registry/src/Format/Json.php
    line 72
    I changed it to:
    throw new RuntimeException(sprintf(‘Error decoding JSON data: %s the bad data is: %s’, json_last_error_msg(), $data));

    so I could actually see the data.
    what I saw was:
    Error decoding JSON data: object property name separator ‘:’ expected the bad data is: {«»}
    ok, so it looks like the bad data is {«»}. Is this really invalid JSON? I checked via:
    http://jsonlint.com/#
    and it sure enough is. Valid would be something like:
    {
    «»: «»
    }
    So off to find the culprit.
    Did a sql query on extensions and came up dry, then:
    select id, title, module, params from efzkh_modules where params like ‘%{«»}%’;
    +—-+—————+——————-+———+
    | id | title | module | params |
    +—-+—————+——————-+———+
    | 2 | Login | mod_login | {«»} |
    | 5 | Menu Stats | mod_stats | {«»} |
    | 11 | Footer | mod_footer | {«»} |
    | 14 | User Status | mod_status | {«»} |
    | 26 | Related Items | mod_related_items | {«»} |
    | 32 | Wrapper | mod_wrapper | {«»} |
    | 34 | Feed Display | mod_feed | {«»} |
    | 36 | Syndication | mod_syndicate | {«»} |
    +—-+—————+——————-+———+

    found 8 modules.
    so we nuke them:
    update efzkh_modules set params = » where params like ‘%{«»}%’;

    and the blue screen of death has been banished. I can successfully log in to the admin side now.

    Brent Laminack

  • Resident234

Есть Joomla! 3.9.24 + php-fpm 7.4
Вообщем, возникает ситуация: в компоненте «JomSocial» я в обсуждения, вставляю статью, жму сохранить, и выдаётся ошибка:
>>
0 — Error decoding JSON data: Syntax error
<<
В отладке нашёл место для прописи «var_dump», и выяснелось что ошибка вылазиет когда длинна входной строки достигает 65535. Собственно — как решить вопрос? Какие лимиты выкручивать?

Текст русский отправляется, html код(он сохраняется). Все русские знаки преобразуются в «uXXXX» и вот отсюда и такое количество символов.


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

    более года назад

  • 290 просмотров

Решение найдено.
Есть таблицы:
#__community_notifications
#__community_activities
#__community_groups_discuss
#__community_mailq
В них есть поля, куда записывается информация об обсуждении(напомню: компонент JomSocial, в обсуждение пытаюсь запихнуть текст длинной более 65535) — выдаётся ошибка, т.к. в одной или более таблице есть поля с «длинной поля» до 65535 символов — возникает ошибка. Нужно изменить длинну поля на большее(Тип поля: mediumtext — спасибо Сергей delphinpro, Дмитрий вы были правы. Просто не в 1-о место записываются данные). Название полей не даю т.к.: если вы сами не можете разобраться — лучше не лезте туда сами.

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

Колонка в базе данных, в которой хранится json строка, имеет длину 65535 байт
Учитывая, что компонент довольно старый, вероятно она имеет тип TEXT, а не JSON. Можно попробовать поменять на MEDIUMTEXT.


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

09 февр. 2023, в 13:58

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

09 февр. 2023, в 13:28

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

09 февр. 2023, в 13:09

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

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

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error 0 checking dll signature far cry 4 как исправить
  • Error 0 887a0006
  • Error 0 534134 model id 1800 does
  • Errno список ошибок
  • Errno error codes

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии