0 Пользователей и 1 Гость просматривают эту тему.
- 4 Ответов
- 1937 Просмотров
Установил плагин canonical-links-all-in-one-3.46 в его настройках можно перечислить ссылки чтобы не канонические ссылки ссылались на канонические.
Делается это в таком формате
http://site.com/12/358-324/1281-no-cannonikal|http://site.com/12/356-322/1260-cannonikal
http://site.com/12/365-331/1399-no-cannonikal|http://site.com/12/356-322/1260-cannonikal
Проверил, все отлично — все работает.
Загнал туда 200 строк — все ок, все работает.
Загнал туда 650 строк и сайт умер с ошибкой — Error decoding JSON data: Control character error, possibly incorrectly encoded
Ни работало ничего, помогло только выключение плагина через админку.
Первое что пришло на ум — поля params таблицы _extensions не хватает для переваривания моего объем ссылок, изменил тип с text на longtext
Но к сожалению это не помогло. Подскажите, пожалуйста, как можно победить проблему?
Все вопрос закрыт, оказывается изменение типа поля помогло. После этого я удалил и установил плагин заново и он нормально переварил такой объем ссылок.
Привет всем, у меня подобная штука случилась, может поможет кто разобраться. Выдавала ошибку: «Не удалось сохранить из-за ошибки: Содержимое превышает допустимые лимиты.» Почитал в интернете и поменял в таблице fulltext вместо mediumtext, на longtext. Ничего не произошло. Пошел дальше в интернет, нашел что в файле librariessrcTableModule.php нужно найти «Prevent to save too large content > 65535». Я нашел и поменял везде цифру 65535 на 665535, то есть впереди зачем то добавил 6 и сохранил. После этого не работает ни сайт, ни админка. Что делать, подскажите пожалуйста, сайт принадлежит транспортной компании, сейчас клиенты заходят и видят ошибку 404. Очень просим о помощи.
На данный момент в админке вот такая ошибка: Произошла ошибка
0 Error decoding JSON data: Control character error, possibly incorrectly encoded
« Последнее редактирование: 29.11.2022, 18:38:33 от cheltcom_ru »
Записан
На данный момент в админке вот такая ошибка: Произошла ошибка
0 Error decoding JSON data: Control character error, possibly incorrectly encoded
Файлы трогать не надо было (скорее всего) верните как было. Изменение типа поля — это верное решение. Но, кроме этого, надо было найти в БД проблемную запись (скорее всего она последняя — с максимальным id) и исправить или удалить в ней json, который записался туда не полностью (обрезался) и поэтому теперь не может распаковаться. От этого, судя по всему, ошибка и вылазит. Само изменение ширины поля данные не исправит.
Спасибо большое, обратился программисту, вопрос решили.
Это краткая статья о наиболее вероятных проблемах с json_encode и их решениях. Иногда при кодировании данных в json, с помощью json_encode в php, мы получаем не тот результат который ожидаем. Я выделил три наиболее частые проблемы с которыми сталкиваются программисты:
- доступ к полям
- кодировка текстовых значений
- цифровые значения
Доступ к полям
Проблема заключается в том что json_encode имеет доступ только к публичным полям объекта. Например если у вас есть класс
class Example {
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
public function __construct($public, $protected, $private)
{
$this->publicProperty = $public;
$this->protectedProperty = $protected;
$this->privateProperty = $private;
}
}
то результатом выполнения следующего кода будет:
$obj = new Example("some", "value", "here");
echo json_encode($obj);
// {"publicProperty":"some"}
как видно в результирующий json были включены только публичные поля.
Что же делать если нужны все поля?
Решение
Для php < 5.4:
нам необходимо будет реализовать в классе метод который будет возвращать готовый json. Т.к. внутри класса есть доступ ко всем полям можно сформировать правильное представление объекта для json_encode
class Example {
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
public function __construct($public, $protected, $private)
{
$this->publicProperty = $public;
$this->protectedProperty = $protected;
$this->privateProperty = $private;
}
public function toJson()
{
return json_encode([
'publicProperty' => $this->publicProperty,
'protectedProperty' => $this->protectedProperty,
'privateProperty' => $this->privateProperty,
]);
}
}
Для получение json-a c объекта теперь нужно пользоваться методом toJson, а не прямым применением json_encode к объекту
$obj = new Example("some", "value", "here");
echo $obj->toJson();
Для php >= 5.4:
достаточно будет реализовать интерфейс JsonSerializable для нашего класса, что подразумевает добавление метода jsonSerialize который будет возвращать структуру представляющую объект для json_encode
class Example implements JsonSerializable
{
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
public function __construct($public, $protected, $private)
{
$this->publicProperty = $public;
$this->protectedProperty = $protected;
$this->privateProperty = $private;
}
public function jsonSerialize()
{
return [
'publicProperty' => $this->publicProperty,
'protectedProperty' => $this->protectedProperty,
'privateProperty' => $this->privateProperty,
];
}
}
Теперь мы можем использовать json_encode как и раньше
$obj = new Example("some", "value", "here");
echo json_encode($obj);
// {"publicProperty":"some","protectedProperty":"value","privateProperty":"here"}
Почему не стоит использовать подход с toJson методом?
Многие наверно заметили что подход с созданием метода возвращающего json может быть использован и в версиях php >= 5.4. Так почему же не воспользоваться им? Все дело в том что ваш класс может быть использован как часть иной структуры данных
echo json_encode([
'status' => true,
'message' => 'some message',
'data' => new Example("some", "value", "here"),
]);
и результат уже будет совсем другой.
Также класс может использоваться другими программистами, для которых такой тип получение json-а с объекта может быть не совсем очевиден.
Что если у меня очень много полей в класcе?
В таком случае можно воспользоваться функцией get_object_vars
class Example implements JsonSerializable
{
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
protected $someProp1;
...
protected $someProp100500;
public function __construct($public, $protected, $private)
{
$this->publicProperty = $public;
$this->protectedProperty = $protected;
$this->privateProperty = $private;
}
public function jsonSerialize()
{
$fields = get_object_vars($this);
// что-то делаем ...
return $fields;
}
}
А если нужно private-поля, из класса, который нет возможности редактировать?
Может получиться ситуация когда нужно получить private поля (именно private, т.к. доступ к protected полям можно получить через наследование) в json-е. В таком случае необходимо будет воспользоваться рефлексией:
class Example
{
public $publicProperty = "someValue";
protected $protectedProperty;
private $privateProperty1;
private $privateProperty2;
private $privateProperty3;
public function __construct($privateProperty1, $privateProperty2, $privateProperty3, $protectedProperty)
{
$this->protectedProperty = $protectedProperty;
$this->privateProperty1 = $privateProperty1;
$this->privateProperty2 = $privateProperty2;
$this->privateProperty3 = $privateProperty3;
}
}
$obj = new Example("value1", 12, "21E021", false);
$reflection = new ReflectionClass($obj);
$public = [];
foreach ($reflection->getProperties() as $property) {
$property->setAccessible(true);
$public[$property->getName()] = $property->getValue($obj);
}
echo json_encode($public);
//{"publicProperty":"someValue","protectedProperty":false,"privateProperty1":"value1","privateProperty2":12,"privateProperty3":"21E021"}
Кодировка текстовых значений
Кириллица и другие знаки в UTF8
Второй тип распространённых проблем с json_encode это проблемы с кодировкой. Часто текстовые значения которые нужно кодировать в json имеют в себе символы в UTF8 (в том числе кириллица) в результате эти символы будут представлены в виде кодов:
echo json_encode("кириллица or ₳ ƒ 元 ﷼ ₨ ௹ ¥ ₴ £ ฿ $");
// "u043au0438u0440u0438u043bu043bu0438u0446u0430 or u20b3 u0192 u5143 ufdfc u20a8 u0bf9 uffe5 u20b4 uffe1 u0e3f uff04"
Отображение таких символов лечится очень просто — добавлением флага JSON_UNESCAPED_UNICODE вторым аргументом к функции json_encode:
echo json_encode("кириллица or ₳ ƒ 元 ﷼ ₨ ௹ ¥ ₴ £ ฿ $", JSON_UNESCAPED_UNICODE);
// "кириллица or ₳ ƒ 元 ﷼ ₨ ௹ ¥ ₴ £ ฿ $"
Символы в других кодировках
Функция json_encode воспринимает строковые значения как строки в UTF8, что может вызвать ошибку, если кодировка другая. Рассмотрим маленький кусочек кода (данный пример кода максимально упрощен для демонстрации проблемной ситуации)
echo json_encode(["p" => $_GET['p']]);
На первый взгляд ничего не предвещает проблем, да и что здесь может пойти не так? Я тоже так думал. В подавляющем большинстве случаев все будет работать, и по этой причине поиск проблемы занял у меня несколько больше времени, когда я впервые столкнулся с тем что результатом json_encode было false.
Для воссоздания такой ситуации предположим что p=%EF%F2%E8%F6%E0 (на пример: localhost?=%EF%F2%E8%F6%E0 ).
*Переменные в суперглобальных массивах $_GET и $_REQUEST уже декодированы.
$decoded = urldecode("%EF%F2%E8%F6%E0");
var_dump(json_encode($decoded));
// bool(false)
var_dump(json_last_error_msg());
// string(56) "Malformed UTF-8 characters, possibly incorrectly encoded"
Как можно увидеть из ошибки: проблема с кодировкой переданной строки (это не UTF8). Решение проблемы очевидное — привести значение в UTF8
$decoded = urldecode("%EF%F2%E8%F6%E0");
$utf8 = utf8_encode($decoded);
echo json_encode($utf8);
// "ïòèöà"
Цифровые значения
Последняя типовая ошибка связана с кодированием числовых значений.
Например:
echo json_encode(["string_float" => "3.0"]);
// {"string_float":"3.0"}
Как известно php не строго типизированный язык и позволяет использовать числа в виде строки, в большинстве случаев это не приводит к ошибкам внутри php приложения. Но так как json очень часто используется для передачи сообщений между приложениями, такой формат записи числа может вызвать проблемы в другом приложении. Желательно использовать флаг JSON_NUMERIC_CHECK:
echo json_encode(["string_float" => "3.0"], JSON_NUMERIC_CHECK);
// {"string_float":3}
Уже лучше. Но как видим «3.0» превратилось в 3, что в большинстве случаев будет интерпретировано как int. Используем еще один флаг JSON_PRESERVE_ZERO_FRACTION для корректного преобразования в float:
echo json_encode(["string_float" => "3.0"], JSON_NUMERIC_CHECK | JSON_PRESERVE_ZERO_FRACTION);
// {"string_float":3.0}
Прошу также обратить внимание на следующий фрагмент кода, что иллюстрирует ряд возможных проблем с json_encode и числовыми значениями:
$data = [
"0000021", // нули слева
6.12345678910111213, // много знаков после точки (будет округленно)
"+81011321515", // телефон
"21E021", // экспоненциальная запись
];
echo json_encode($data, JSON_NUMERIC_CHECK);
//[
// 21,
// 6.1234567891011,
// 81011321515,
// 2.1e+22
// ]
Спасибо за прочтение.
Буду рад увидеть в комментариях описание проблем, с которыми вы сталкивались, что не были упомянуты в статье
- Index
- Recent Topics
- Search
-
Log in
- Forum
- K2 Community Forum
- English K2 Community
- [SOLVED] 0 Error decoding JSON data: Control character error, possibl
6 years 3 months ago #158670
by by Alexander
HI, after upgrading Joomla 3.6.2 to 3.6.3 I get this error when I want to edit a k2 article or make a new one.
0 Error decoding JSON data: Control character error, possibly incorrectly encoded
Where do I look for this? Is there an update for it?
Please Log in or Create an account to join the conversation.
6 years 3 months ago #158686
by Krikor Boghossian
Can you try disabling error reporting?
Which file is throwing that error?
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 ago #158710
by by Alexander
Error reporting is off. Here is a screenshot.
Please Log in or Create an account to join the conversation.
6 years 3 months ago — 6 years 3 months ago #158711
by by Alexander
Last edit: 6 years 3 months ago by by Alexander.
Please Log in or Create an account to join the conversation.
6 years 3 months ago #158716
by Krikor Boghossian
Can you check on your error_log which file is throwing the error?
I am asking this because I cannot reproduce this behaviour using K2 2.7.1 and 2.7.2 DEV build.
It is possible that a 3rd party K2 extension is causing this issue.
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 ago #158717
by Krikor Boghossian
Can you check on your error_log which file is throwing the error?
I am asking this because I cannot reproduce this behaviour using K2 2.7.1 and 2.7.2 DEV build.
It is possible that a 3rd party K2 extension is causing this issue.
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 ago #158735
by by Alexander
I use a template from Gavick, and I do not use any thirdparty k2 extensions. I only enabled K2 and K2 system plugin and the problem still is there.
Would it help to download a fresh copy of K2 and install it again without losing stuff? Maybe a specific file is corrupt ?
This is what I typed to Gavick support:
Hi, I want to notify that K2 throws in some problems after updating Joomla (technews) 3.6.2 to 3.6.3. I asked K2 and they asked me 2 things:
1. Check error_log. (Does the template have the errorlog string attached, cause I cannot seem to find the file.)
2. Do you use a third party k2 plugin? In the backend I cannot find any.
I need to be able to reproduce the problem for them and I have 40 websites with k2. The only one that gives me the problem is the one with the odd in it, your newstech template.
The error I get as soon as I want to click on an K2 article:
0 Error decoding JSON data: Control character error, possibly incorrectly encoded
Please Log in or Create an account to join the conversation.
6 years 3 months ago #158737
by Krikor Boghossian
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 ago #158742
by by Alexander
This is a message from Robert Gavick. However, the php version I use is NOT PHP 7.0+, I use PHP 5.5.32.
I do not have any clue with this and I’m pretty f*cked if this can’t be solved.
1. There’s no error found in the error_log file.
2. There’s no k2 third party plugin activated
3. I’ve disabled completely K2 overriden files from TechNews template and the problem still occurs
Additional informations:
I’ve noticed that the problem occurs only on the server with PHP 7.0.x (with PHP 5.6.x there’s no problem).
K2 v.2.7.0 works properly
K2 v.2.7.1 and dev version 2.7.2 don’t work.
Please Log in or Create an account to join the conversation.
6 years 3 months ago #158756
by Alex Mediosavs
Hello, I have the same problem, this happened when you upgrade joomla 3.6.3 and k2 2.7.1
Please Log in or Create an account to join the conversation.
- Forum
- K2 Community Forum
- English K2 Community
- [SOLVED] 0 Error decoding JSON data: Control character error, possibl
Problem
Running the following sample code, json_decoding the memcached value results in the following JSON error messages:
- Syntax error
- Control character error, possibly incorrectly encoded
- Malformed UTF-8 characters, possibly incorrectly encoded
The error message generated cycles through the above list once the JSON encoded string is larger than 2000 characters.
No error messages are generated by just JSON encoding and decoding directly. The only time errors occur is when the value being decoded is retrieve from memcache.
Sample code
<?php
$memcache = new Memcached;
$memcache->addServer('localhost', 11211);
echo "<pre>n";
$arr = array();
for ($i = 0; $i < 1000; $i++) {
$arr[] = "abcdefghij";
$json_str_in = json_encode($arr);
if (FALSE === $memcache->set('test/jsondata', $json_str_in, 2)) {
echo "getResultCode = " . Memcached::getResultCode() . PHP_EOL;
exit;
}
$json_str_out = $memcache->get('test/jsondata');
json_decode($json_str_in, TRUE);
if (JSON_ERROR_NONE !== json_last_error()) {
printf(
'strlen of source value: %d, json_decode of source value: [%s]' . PHP_EOL,
strlen($json_str_in),
json_last_error_msg()
);
}
json_decode($json_str_out, TRUE);
if (JSON_ERROR_NONE !== json_last_error()) {
printf(
'strlen of memcached value: %d, json_decode of memcached value: [%s]' . PHP_EOL,
strlen($json_str_out),
json_last_error_msg()
);
}
}
PHP Version
PHP 7.0.5 (cli) (built: Apr 11 2016 15:53:52) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies
with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans
Memcached Config
memcached support => enabled
Version => 3.0.0-dev
libmemcached version => 1.0.18
SASL support => yes
Session support => yes
igbinary support => yes
json support => yes
msgpack support => yes
Directive => Local Value => Master Value
memcached.compression_factor => 1.3 => 1.3
memcached.compression_threshold => 2000 => 2000
memcached.compression_type => fastlz => fastlz
memcached.default_binary_protocol => 0 => 0
memcached.default_connect_timeout => 0 => 0
memcached.default_consistent_hash => 0 => 0
memcached.serializer => igbinary => igbinary
memcached.sess_binary_protocol => 1 => 1
memcached.sess_connect_timeout => 1000 => 1000
memcached.sess_consistent_hash => no value => no value
memcached.sess_lock_expire => 0 => 0
memcached.sess_lock_max_wait => not set => not set
memcached.sess_lock_retries => 5 => 5
memcached.sess_lock_wait => not set => not set
memcached.sess_lock_wait_max => 0 => 0
memcached.sess_lock_wait_min => 0 => 0
memcached.sess_locking => 1 => 1
memcached.sess_number_of_replicas => 0 => 0
memcached.sess_persistent => 0 => 0
memcached.sess_prefix => memc.sess.key. => memc.sess.key.
memcached.sess_randomize_replica_read => no value => no value
memcached.sess_remove_failed_servers => 0 => 0
memcached.sess_sasl_password => no value => no value
memcached.sess_sasl_username => no value => no value
memcached.sess_server_failure_limit => 0 => 0
memcached.store_retry_count => 2 => 2
Memcache Server Version
Error decoding JSON data: Control character error, possibly incorrectly encoded
Discussion in ‘Community’ started by xtrgeo, Aug 7, 2017.
-
This happens when trying to access a list.
Already the latest update from github…
Any ideas?
Attached Files:
-
-
OK, that means there’s some broken JSON in the params of one of your elements.
Unfortunately, the only way to get some clue as to which one is to modify some Joomla core code.
Edit the file:
./libraries/vendor/joomla/registry/src/Format/Json.php
… and around line 72 will be …
if ($decoded === null)
{
throw new RuntimeException(sprintf(‘Error decoding JSON data: %s’, json_last_error_msg()));
}
… modify that to add the actual data to the error message:
if ($decoded === null)
{
throw new RuntimeException(sprintf(‘Error decoding JSON data: %s : the bad data is: %s’, json_last_error_msg(), $data));
}
That should give you some clue as to which one it is. Then of course it has to be fixed, and we have to work out how the bad data got in there.
So do that, and paste the new error message here.
— hugh
-
BTW, this was the result of a change in Joomla code in 3.6.3, which now treats malformed JSON as a fatal error, where as prior to 3.6.3 it would just discard the bad data and return «null». This caused a BIG argument at the end of last year:
https://github.com/joomla/joomla-cms/issues/12460#issuecomment-256219685
… where you can see the main authors of J! getting very angry.
The problem is, although I agree that J! should no longer just silently discard problems in JSON configuration data, I think it should attempt to give some information about what that damaged data is (as per the code change I gave in the previous post) to make it possible to find and fix the problem.
— hugh
-
How! Huge error report…
The error is too big to fit in the message, so I attach it’s rest body in the text file…
Error decoding JSON data: Control character error, possibly incorrectly encoded : the bad data is: {«placeholder»:»»,»password»:»0″,»maxlength»:»255″,»disable»:»0″,»readonly»:»0″,»autocomplete»:»1″,
«speech»:»0″,»advanced_behavior»:»0″,»bootstrap_class»:»input-medium»,
«text_format»:»text»,»integer_length»:»6″,»decimal_length»:»2″,»field_use_number_format»:»0″,
«field_thousand_sep»:»,»,»field_decimal_sep»:».»,»text_format_string»:»»,»field_format_string_blank»:»1″,»text_input_mask»:»»,»text_input_mask_autoclear»:»0″,»text_input_mask_definitions»:»»,»render_as_qrcode»:»0″,»guess_linktype»:»0″,»link_target_options»:»default»,»rel»:»»,»link_title»:»»,»show_in_rss_feed»:»0″,»show_label_in_rss_feed»:»0″,»use_as_rss_enclosure»:»0″,»rollover»:»»,»tipseval»:»0″,»tiplocation»:»top-left»,»labelindetails»:»0″,»labelinlist»:»0″,»comment»:»»,»edit_access»:»1″,»edit_access_user»:»»,»view_access»:»1″,»view_access_user»:»»,»list_view_access»:»1″,»encrypt»:»0″,»store_in_db»:»1″,»can_order»:»1″,»alt_list_heading»:»»,»custom_link»:»»,»custom_link_target»:»»,»custom_link_indetails»:»1″,»use_as_row_class»:»0″,»include_in_list_query»:»1″,»always_render»:»0″,»icon_hovertext»:»1″,»icon_file»:»»,»icon_subdir»:»»,»filter_length»:»20″,»filter_access»:»1″,»full_words_only»:»0″,»filter_required»:»0″,»filter_build_method»:»0″,»filter_groupby»:»text»,»inc_in_adv_search»:»1″,»filter_class»:»input-medium»,»filter_responsive_class»:»»,»tablecss_header_class»:»»,»tablecss_header»:»»,»tablecss_cell_class»:»»,»tablecss_cell»:»»,»sum_on»:»1″,»sum_label»:»Sum»,»sum_access»:»1″,»sum_split»:»»,»avg_on»:»0″,»avg_label»:»Average»,»avg_access»:»1″,»avg_round»:»0″,»avg_split»:»»,»median_on»:»0″,»median_label»:»Median»,»median_access»:»1″,»median_split»:»»,»count_on»:»1″,»count_label»:»Count»,»count_condition»:»»,»count_access»:»1″,»count_split»:»»,»custom_calc_on»:»0″,»custom_calc_label»:»Custom»,»custom_calc_query»:»»,»custom_calc_access»:»1″,»custom_calc_split»:»»,»custom_calc_php»:»»,»validations»:[],»join_val_column_concat»:null,»sum_value_serialized»:»a:320:{i:0;O:8:»stdClass»:4:{s:5:»value»;s:1:»0″;s:5:»label»;s:1:»0″;s:7:»elLabel»;s:6:»risk 0″;s:8:»calLabel»;s:3:»Sum»;}s:5:»Total»;O:8:»stdClass»:6:{s:5:»value»;d:914803.55950701237;s:5:»label»;s:5:»Total»;s:5:»class»;s:10:»splittotal»;s:7:»special»;b:1;s:7:»elLabel»;s:10:»risk Total»;s:8:»calLabel»;s:3:»Sum»;}i:1;O:8:»stdClass»:4:{s:5:»value»;s:18:»115.44000160694122″;s:5:»label»;s:1:»1″;s:7:»elLabel»;s:6:»risk 1″;s:8:»calLabel»;s:3:»Sum»;}i:2;O:8:»stdClass»:4:Attached Files:
-
Hi Hugh
I assume it’s the «list calculation is stored as session data in the element params…» following our Skype session
[26.01.2017 23:46:10] B. Tr?ster: It’s replicatable: a list with calculation is modifying the element’s params on list load
(without error now)
[27.01.2017 00:01:51] Hugh Messenger: yes — when the list loads, it runs the element calculations to be cached, if that list load itself isn’t cached.
[27.01.2017 00:02:18] Hugh Messenger: I can’t figure out what was wrong with that string, but it fails an unserialize as well.
[27.01.2017 00:03:02] Hugh Messenger: theoretically a JSON string can be anything, as long as double quotes are escaped. -
@troester — yup, but what’s puzzling me is why it’s getting this specific error. The issue with the params longer than 65535 should be fixed, although the error msg he attached on the last post shows that the params are truncated. Although I suppose if he just updated, and they haven’t been saved since the update. But the error is talking about «control character error».
@xtrgeo
OK …
So the problem element is the one that has a list calculation with the label «risk Total».
What you’ll have to do is …
With something like phpMyAdmin, look at your #__fabrik_elements table, and see what field type the ‘params’ field is. It should be MEDIUMTEXT, but it may still be TEXT. If it is TEXT, then you need to change the field type to MEDIUMTEXT. This should be safe, you won’t lose any data, as it’s just changing it to a text field type which can store more data. But if you do need to change it to MEDIUMTEXT, back up your database (or at least this table) first.
Then find the element in #__fabrik_elements which is the one that has the «risk Total» calculation on it. Edit that row, and look at the params field. If it really does end in:
<span class=»calclabel»>301
… rather than something like …
<span class=»calclabel»>Total:</span> $7,316.34</dd>n</dl>»}
… ie. is closed with a …
«}
… then you need to delete that calculation entirely, so your params has …
«join_val_column_concat»:null,»sum_value_serialized»:»»}
… rather than …
«join_val_column_concat»:null,»sum_value_serialized»:»… incredible long string that doesn’t have a close quote and curly brace on the end
Once you’ve done that, so the JSON is properly formatted again, you should be able to load the list, or edit and save the element settings, and it should fix itself.
If you params DOES already end with «}, then we need to figure out what is causing the problem.
— hugh
-
Thnks for the detailed reply Hugh.
I followed your directions and I also had to do the same for another element that had calculations also.
Thnkfully, there were no «}» at the end of params and I erase the calculation. Save those elements settings again and everything works fine.
One thing I noticed is that when saving again the element is that it asked it me for confitmation for type change.
The first from float to varchar(255). I choosed no, changed the type in elements settings as decimal and choosed to be seen as number (Yes/No option).
Both elemetns changed to decimal 12,2 type.
Why this happened? Is there any change that something need to be changed in fabrik’s code in order for this error message to be seen again?
-
It depends what version you updated from. We always check to make sure the data type of the underlying field matches whatever type the element is set to. That code has changed slightly over the years.
But I don’t think we’ve ever used any of the FLOAT field types. If you choose «decimal» we use DECIMAL.
So I suspect your fields were set to float by something / someone else.
And no, there’s nothing you need to change to avoid the JSON error.
The problem was that our original #__fabrik_elements table set the ‘params’ field to be of type TEXT, which is limited to 65535 characters. It didn’t occur to us way back then (10 years ago) that if you have a split calculation, on a large table, with a lot of splits, that when we cache the calculation in the params, it could exceed 64k.
Prior to Fabrik 3.7, those params would just get truncated, meaning that the JSON was invalid. Prior to J! 3.6.3, when J! reads the params, if the JSON was invalid it just silently discarded it. As of 3.6.3, they throw that fatal exception you saw.
So … in Fabrik 3.7, as part of our updater code, we change the params field to MEDIUMTEXT, which allows for a few megabytes. We also double check in our code that writes out those params, and if the length is > 65535, we change the field type. That’s in case someone has updated from github, rather than running the actual updater, and the field type hasn’t been changed yet.
Unfortunately, if your params were already truncated when you update to Fabrik 3.7, it’s still going to blow up when anything tries to open that element, and there’s really no way for us to work round that. But now you’ve fixed the affected elements by hand, and changed your params to MEDIUMTEXT, it won’t happen again.
— hugh
Share This Page
Содержание
- Решение типовых проблем с json_encode (PHP)
- Доступ к полям
- Решение
- Почему не стоит использовать подход с toJson методом?
- Что если у меня очень много полей в класcе?
- А если нужно private-поля, из класса, который нет возможности редактировать?
- Кодировка текстовых значений
- Кириллица и другие знаки в UTF8
- Символы в других кодировках
- Цифровые значения
- Memcached corrupting JSON encoded data #250
- Comments
- JoomlaWorks
- PHP JSON Debugging JSON errors
- Example
- json_last_error_msg
- json_last_error
- Predefined Constants
Решение типовых проблем с json_encode (PHP)
Это краткая статья о наиболее вероятных проблемах с json_encode и их решениях. Иногда при кодировании данных в json, с помощью json_encode в php, мы получаем не тот результат который ожидаем. Я выделил три наиболее частые проблемы с которыми сталкиваются программисты:
- доступ к полям
- кодировка текстовых значений
- цифровые значения
Доступ к полям
Проблема заключается в том что json_encode имеет доступ только к публичным полям объекта. Например если у вас есть класс
то результатом выполнения следующего кода будет:
как видно в результирующий json были включены только публичные поля.
Что же делать если нужны все поля?
Решение
Для php = 5.4:
достаточно будет реализовать интерфейс JsonSerializable для нашего класса, что подразумевает добавление метода jsonSerialize который будет возвращать структуру представляющую объект для json_encode
Теперь мы можем использовать json_encode как и раньше
Почему не стоит использовать подход с toJson методом?
Многие наверно заметили что подход с созданием метода возвращающего json может быть использован и в версиях php >= 5.4. Так почему же не воспользоваться им? Все дело в том что ваш класс может быть использован как часть иной структуры данных
и результат уже будет совсем другой.
Также класс может использоваться другими программистами, для которых такой тип получение json-а с объекта может быть не совсем очевиден.
Что если у меня очень много полей в класcе?
В таком случае можно воспользоваться функцией get_object_vars
А если нужно private-поля, из класса, который нет возможности редактировать?
Может получиться ситуация когда нужно получить private поля (именно private, т.к. доступ к protected полям можно получить через наследование) в json-е. В таком случае необходимо будет воспользоваться рефлексией:
Кодировка текстовых значений
Кириллица и другие знаки в UTF8
Второй тип распространённых проблем с json_encode это проблемы с кодировкой. Часто текстовые значения которые нужно кодировать в json имеют в себе символы в UTF8 (в том числе кириллица) в результате эти символы будут представлены в виде кодов:
Отображение таких символов лечится очень просто — добавлением флага JSON_UNESCAPED_UNICODE вторым аргументом к функции json_encode:
Символы в других кодировках
Функция json_encode воспринимает строковые значения как строки в UTF8, что может вызвать ошибку, если кодировка другая. Рассмотрим маленький кусочек кода (данный пример кода максимально упрощен для демонстрации проблемной ситуации)
На первый взгляд ничего не предвещает проблем, да и что здесь может пойти не так? Я тоже так думал. В подавляющем большинстве случаев все будет работать, и по этой причине поиск проблемы занял у меня несколько больше времени, когда я впервые столкнулся с тем что результатом json_encode было false.
Для воссоздания такой ситуации предположим что p=%EF%F2%E8%F6%E0 (на пример: localhost?=%EF%F2%E8%F6%E0 ).
*Переменные в суперглобальных массивах $_GET и $_REQUEST уже декодированы.
Как можно увидеть из ошибки: проблема с кодировкой переданной строки (это не UTF8). Решение проблемы очевидное — привести значение в UTF8
Цифровые значения
Последняя типовая ошибка связана с кодированием числовых значений.
Как известно php не строго типизированный язык и позволяет использовать числа в виде строки, в большинстве случаев это не приводит к ошибкам внутри php приложения. Но так как json очень часто используется для передачи сообщений между приложениями, такой формат записи числа может вызвать проблемы в другом приложении. Желательно использовать флаг JSON_NUMERIC_CHECK:
Уже лучше. Но как видим «3.0» превратилось в 3, что в большинстве случаев будет интерпретировано как int. Используем еще один флаг JSON_PRESERVE_ZERO_FRACTION для корректного преобразования в float:
Прошу также обратить внимание на следующий фрагмент кода, что иллюстрирует ряд возможных проблем с json_encode и числовыми значениями:
Спасибо за прочтение.
Буду рад увидеть в комментариях описание проблем, с которыми вы сталкивались, что не были упомянуты в статье
Источник
Memcached corrupting JSON encoded data #250
Running the following sample code, json_decoding the memcached value results in the following JSON error messages:
- Syntax error
- Control character error, possibly incorrectly encoded
- Malformed UTF-8 characters, possibly incorrectly encoded
The error message generated cycles through the above list once the JSON encoded string is larger than 2000 characters.
No error messages are generated by just JSON encoding and decoding directly. The only time errors occur is when the value being decoded is retrieve from memcache.
Memcache Server Version
The text was updated successfully, but these errors were encountered:
We noticed this very same problem.
It seems that when it does the decompression of compressed values (see the 2000B default threshold) it adds somewhere some non-utf8 character(s) that I couldn’t find.
i’m having the same issue with PHP serialized data. A workaround:
memcached.compression_threshold=9999999999
we found a potential bug in decompress path. and the PR works for us so far. please try and see if the fix works for you
#252
@wetcoast @arisro @ftzdomino could you try if the PR #252 works for you?
we found a potential bug in decompress path. and the PR works for us so far. please try and see if the fix works for you
#252
works for us. thanks!
Works fine for us too! Thank you so much for the fix @dictcp. One step closer to the PHP7 version release. 🙂
I want to also add that we upgraded our production to php7, using the packages from Ondrej’s repo. We used as a workaround for this (we are json_encoding only one key) doing a utf8_encode() when fetching from memcached, before json_decoding.
We didn’t notice yet (in 10 days) any other issues with the extension for our use cases, of course! We will have a bigger traffic spike this weekend, we’ll monitor it and report if we have any performance issues with it.
Источник
JoomlaWorks
- by Alexander
- Topic Author —>
- Offline
- New Member
HI, after upgrading Joomla 3.6.2 to 3.6.3 I get this error when I want to edit a k2 article or make a new one.
0 Error decoding JSON data: Control character error, possibly incorrectly encoded
Where do I look for this? Is there an update for it?
Please Log in or Create an account to join the conversation.
- Krikor Boghossian
- —>
- Offline
- Platinum Member
Please Log in or Create an account to join the conversation.
- by Alexander
- Topic Author —>
- Offline
- New Member
Please Log in or Create an account to join the conversation.
- by Alexander
- Topic Author —>
- Offline
- New Member
Please Log in or Create an account to join the conversation.
- Krikor Boghossian
- —>
- Offline
- Platinum Member
Can you check on your error_log which file is throwing the error?
I am asking this because I cannot reproduce this behaviour using K2 2.7.1 and 2.7.2 DEV build.
It is possible that a 3rd party K2 extension is causing this issue.
Please Log in or Create an account to join the conversation.
- Krikor Boghossian
- —>
- Offline
- Platinum Member
Can you check on your error_log which file is throwing the error?
I am asking this because I cannot reproduce this behaviour using K2 2.7.1 and 2.7.2 DEV build.
It is possible that a 3rd party K2 extension is causing this issue.
Please Log in or Create an account to join the conversation.
- by Alexander
- Topic Author —>
- Offline
- New Member
I use a template from Gavick, and I do not use any thirdparty k2 extensions. I only enabled K2 and K2 system plugin and the problem still is there.
Would it help to download a fresh copy of K2 and install it again without losing stuff? Maybe a specific file is corrupt ?
This is what I typed to Gavick support:
Hi, I want to notify that K2 throws in some problems after updating Joomla (technews) 3.6.2 to 3.6.3. I asked K2 and they asked me 2 things:
1. Check error_log. (Does the template have the errorlog string attached, cause I cannot seem to find the file.)
2. Do you use a third party k2 plugin? In the backend I cannot find any.
I need to be able to reproduce the problem for them and I have 40 websites with k2. The only one that gives me the problem is the one with the odd in it, your newstech template.
The error I get as soon as I want to click on an K2 article:
0 Error decoding JSON data: Control character error, possibly incorrectly encoded
Please Log in or Create an account to join the conversation.
Источник
PHP JSON Debugging JSON errors
Example
When json_encode or json_decode fails to parse the string provided, it will return false . PHP itself will not raise any errors or warnings when this happens, the onus is on the user to use the json_last_error() and json_last_error_msg() functions to check if an error occurred and act accordingly in your application (debug it, show an error message, etc.).
The following example shows a common error when working with JSON, a failure to decode/encode a JSON string (due to the passing of a bad UTF-8 encoded string, for example).
json_last_error_msg
json_last_error_msg() returns a human readable message of the last error that occurred when trying to encode/decode a string.
- This function will always return a string, even if no error occurred.
The default non-error string is No Error - It will return false if some other (unknown) error occurred
- Careful when using this in loops, as json_last_error_msg will be overridden on each iteration.
You should only use this function to get the message for display, not to test against in control statements.
This function doesn’t exist before PHP 5.5. Here is a polyfill implementation:
json_last_error
json_last_error() returns an integer mapped to one of the pre-defined constants provided by PHP.
Источник
Predefined Constants
The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.
The following constants indicate the type of error returned by json_last_error() or stored as the code of a JsonException .
JSON_ERROR_NONE ( int ) No error has occurred. JSON_ERROR_DEPTH ( int ) The maximum stack depth has been exceeded. JSON_ERROR_STATE_MISMATCH ( int ) Occurs with underflow or with the modes mismatch. JSON_ERROR_CTRL_CHAR ( int ) Control character error, possibly incorrectly encoded. JSON_ERROR_SYNTAX ( int ) Syntax error. JSON_ERROR_UTF8 ( int ) Malformed UTF-8 characters, possibly incorrectly encoded. JSON_ERROR_RECURSION ( int ) The object or array passed to json_encode() include recursive references and cannot be encoded. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, null will be encoded in the place of the recursive reference. JSON_ERROR_INF_OR_NAN ( int ) The value passed to json_encode() includes either NAN or INF . If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, 0 will be encoded in the place of these special numbers. JSON_ERROR_UNSUPPORTED_TYPE ( int ) A value of an unsupported type was given to json_encode() , such as a resource. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, null will be encoded in the place of the unsupported value. JSON_ERROR_INVALID_PROPERTY_NAME ( int ) A key starting with u0000 character was in the string passed to json_decode() when decoding a JSON object into a PHP object. JSON_ERROR_UTF16 ( int ) Single unpaired UTF-16 surrogate in unicode escape contained in the JSON string passed to json_decode() .
The following constants can be combined to form options for json_decode() .
JSON_BIGINT_AS_STRING ( int ) Decodes large integers as their original string value. JSON_OBJECT_AS_ARRAY ( int ) Decodes JSON objects as PHP array. This option can be added automatically by calling json_decode() with the second parameter equal to true .
The following constants can be combined to form options for json_encode() .
JSON_HEX_TAG ( int ) All are converted to u003C and u003E. JSON_HEX_AMP ( int ) All & are converted to u0026. JSON_HEX_APOS ( int ) All ‘ are converted to u0027. JSON_HEX_QUOT ( int ) All » are converted to u0022. JSON_FORCE_OBJECT ( int ) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. JSON_NUMERIC_CHECK ( int ) Encodes numeric strings as numbers. JSON_PRETTY_PRINT ( int ) Use whitespace in returned data to format it. JSON_UNESCAPED_SLASHES ( int ) Don’t escape / . JSON_UNESCAPED_UNICODE ( int ) Encode multibyte Unicode characters literally (default is to escape as uXXXX). JSON_PARTIAL_OUTPUT_ON_ERROR ( int ) Substitute some unencodable values instead of failing. JSON_PRESERVE_ZERO_FRACTION ( int ) Ensures that float values are always encoded as a float value. JSON_UNESCAPED_LINE_TERMINATORS ( int ) The line terminators are kept unescaped when JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was before PHP 7.1 without this constant. Available as of PHP 7.1.0.
The following constants can be combined to form options for json_decode() and json_encode() .
JSON_INVALID_UTF8_IGNORE ( int ) Ignore invalid UTF-8 characters. Available as of PHP 7.2.0. JSON_INVALID_UTF8_SUBSTITUTE ( int ) Convert invalid UTF-8 characters to xfffd (Unicode Character ‘REPLACEMENT CHARACTER’) Available as of PHP 7.2.0. JSON_THROW_ON_ERROR ( int ) Throws JsonException if an error occurs instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg() . JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR . Available as of PHP 7.3.0.
Источник
Не открываются пользовательские группы после обновления (проблема с кодировкой)
Пользователь 4606427 Заглянувший Сообщений: 3 |
#1 22.06.2022 21:45:46 После последних обновлений портала (коробка), не отображаются содержимое пользовательских групп. При открытии любой группы (даже созданную только что) получаю такое: Часть лога /var/log/php/exceptions.log
|
||
Пользователь 5224375 Заглянувший Сообщений: 3 |
#2 23.06.2022 11:25:40 Та же самая проблема, перестали работать гриппы и проекты, причем если локализацию изменить на [ru] с [ua] все работает:
———- |
||
Пользователь 4490686 Заглянувший Сообщений: 3 |
#3 05.07.2022 10:29:51 Та же проблема с кодировкой.
Как решить? (она появилась после обновления bitrix) |
||
Пользователь 4490686 Заглянувший Сообщений: 3 |
#4 05.07.2022 14:10:04 Проблема с кодировкой . Бывает появляется после обновления сайта. https://www.1c-bitrix.ru/download/files/scripts/convert_utf8.php (если сайт на utf8 был) . https://dev.1c-bitrix.ru/community/blogs/howto/1466.php |
(PHP 5 >= 5.3.0, PHP 7, PHP
json_last_error — Returns the last error occurred
Description
json_last_error(): int
Parameters
This function has no parameters.
Return Values
Returns an integer, the value can be one of the following
constants:
Constant | Meaning | Availability |
---|---|---|
JSON_ERROR_NONE |
No error has occurred | |
JSON_ERROR_DEPTH |
The maximum stack depth has been exceeded | |
JSON_ERROR_STATE_MISMATCH |
Invalid or malformed JSON | |
JSON_ERROR_CTRL_CHAR |
Control character error, possibly incorrectly encoded | |
JSON_ERROR_SYNTAX |
Syntax error | |
JSON_ERROR_UTF8 |
Malformed UTF-8 characters, possibly incorrectly encoded | |
JSON_ERROR_RECURSION |
One or more recursive references in the value to be encoded | |
JSON_ERROR_INF_OR_NAN |
One or moreNAN or INF values in the value to be encoded |
|
JSON_ERROR_UNSUPPORTED_TYPE |
A value of a type that cannot be encoded was given | |
JSON_ERROR_INVALID_PROPERTY_NAME |
A property name that cannot be encoded was given | |
JSON_ERROR_UTF16 |
Malformed UTF-16 characters, possibly incorrectly encoded |
Examples
Example #1 json_last_error() example
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach (
$json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (
json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo
PHP_EOL;
}
?>
The above example will output:
Decoding: {"Organization": "PHP Documentation Team"} - No errors Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON
Example #2 json_last_error() with json_encode()
<?php
// An invalid UTF8 sequence
$text = "xB1x31";$json = json_encode($text);
$error = json_last_error();var_dump($json, $error === JSON_ERROR_UTF8);
?>
The above example will output:
string(4) "null" bool(true)
Example #3 json_last_error() and JSON_THROW_ON_ERROR
<?php
// An invalid UTF8 sequence which causes JSON_ERROR_UTF8
json_encode("xB1x31");// The following does not cause a JSON error
json_encode('okay', JSON_THROW_ON_ERROR);// The global error state has not been changed by the former json_encode()
var_dump(json_last_error() === JSON_ERROR_UTF8);
?>
The above example will output:
See Also
- json_last_error_msg() — Returns the error string of the last json_encode() or json_decode() call
- json_decode() — Decodes a JSON string
- json_encode() — Returns the JSON representation of a value
jimmetry at gmail dot com ¶
11 years ago
While this can obviously change between versions, the current error codes are as follows:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
I'm only posting these for people who may be trying to understand why specific JSON files are not being decoded. Please do not hard-code these numbers into an error handler routine.
praveenscience at gmail dot com ¶
8 years ago
I used this simple script, flicked from StackOverflow to escape from the function failing:
<?php
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
?>
Cheers,
Praveen Kumar!
msxcms at bmforum dot com ¶
5 years ago
use this code with mb_convert_encoding, you can json_encode some corrupt UTF-8 chars
function safe_json_encode($value, $options = 0, $depth = 512) {
$encoded = json_encode($value, $options, $depth);
if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
$encoded = json_encode(utf8ize($value), $options, $depth);
}
return $encoded;
}
function utf8ize($mixed) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}
hemono at gmail dot com ¶
7 years ago
when json_decode a empty string, PHP7 will trigger an Syntax error:
<?php
json_decode("");
var_dump(json_last_error(), json_last_error_msg());// PHP 7
int(4)
string(12) "Syntax error"// PHP 5
int(0)
string(8) "No error"
George Dimitriadis ¶
6 years ago
Just adding this note since I had to code this for the actual values reference.
<?phpecho JSON_ERROR_NONE . ' JSON_ERROR_NONE' . '<br />';
echo JSON_ERROR_DEPTH . ' JSON_ERROR_DEPTH' . '<br />';
echo JSON_ERROR_STATE_MISMATCH . ' JSON_ERROR_STATE_MISMATCH' . '<br />';
echo JSON_ERROR_CTRL_CHAR . ' JSON_ERROR_CTRL_CHAR' . '<br />';
echo JSON_ERROR_SYNTAX . ' JSON_ERROR_SYNTAX' . '<br />';
echo JSON_ERROR_UTF8 . ' JSON_ERROR_UTF8' . '<br />';
echo JSON_ERROR_RECURSION . ' JSON_ERROR_RECURSION' . '<br />';
echo JSON_ERROR_INF_OR_NAN . ' JSON_ERROR_INF_OR_NAN' . '<br />';
echo JSON_ERROR_UNSUPPORTED_TYPE . ' JSON_ERROR_UNSUPPORTED_TYPE' . '<br />';/*
The above outputs :
0 JSON_ERROR_NONE
1 JSON_ERROR_DEPTH
2 JSON_ERROR_STATE_MISMATCH
3 JSON_ERROR_CTRL_CHAR
4 JSON_ERROR_SYNTAX
5 JSON_ERROR_UTF8
6 JSON_ERROR_RECURSION
7 JSON_ERROR_INF_OR_NAN
8 JSON_ERROR_UNSUPPORTED_TYPE
*/?>
wedge at atlanteans dot net ¶
4 years ago
here is a small updated version of utf8ize that has the following addition :
* It uses iconv instead of utf8_encode for potentially better result.
* It adds the support of objects variable
* It also update array key value (in a case I met I had to utf8ize the key as well as those were generated from a user input value)
Here is the code.
<?php
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
unset($d[$k]);
$d[utf8ize($k)] = utf8ize($v);
}
} else if (is_object($d)) {
$objVars = get_object_vars($d);
foreach($objVars as $key => $value) {
$d->$key = utf8ize($value);
}
} else if (is_string ($d)) {
return iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($d));
}
return $d;
}
?>
williamprogphp at yahoo dot com dot br ¶
9 years ago
This is a quite simple and functional trick to validate JSON's strings.
<?phpfunction json_validate($string) {
if (is_string($string)) {
@json_decode($string);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
echo (json_validate('{"test": "valid JSON"}') ? "It's a JSON" : "NOT is a JSON"); // prints 'It's a JSON'
echo (json_validate('{test: valid JSON}') ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to missing quotes
echo (json_validate(array()) ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to a non-string argument
?>
Cheers
у меня есть этот объект JSON, хранящийся в текстовом файле:
{
"MySQL": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"DatabaseName": "(dbname)"
},
"Ftp": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"RootFolder": "(rf)"
},
"BasePath": "../../bin/",
"NotesAppPath": "notas",
"SearchAppPath": "buscar",
"BaseUrl": "http://montemaiztusitio.com.ar",
"InitialExtensions": [
"nem.mysqlhandler",
"nem.string",
"nem.colour",
"nem.filesystem",
"nem.rss",
"nem.date",
"nem.template",
"nem.media",
"nem.measuring",
"nem.weather",
"nem.currency"
],
"MediaPath": "media",
"MediaGalleriesTable": "journal_media_galleries",
"MediaTable": "journal_media",
"Journal": {
"AllowedAdFileFormats": [
"flv:1",
"jpg:2",
"gif:3",
"png:4",
"swf:5"
],
"AdColumnId": "3",
"RSSLinkFormat": "%DOMAIN%/notas/%YEAR%-%MONTH%-%DAY%/%TITLE%/",
"FrontendLayout": "Flat",
"AdPath": "ad",
"SiteTitle": "Monte Maíz: Tu Sitio",
"GlobalSiteDescription": "Periódico local de Monte Maíz.",
"MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
"TemplatePath": "templates",
"WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
"WeatherMeasureType": "1",
"CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
"TimesSingular": "vez",
"TimesPlural": "veces"
}
}
когда я пытаюсь декодировать его с json_decode()
, он возвращает NULL. Почему?
Файл читается (я пробовал Эхо file_get_contents()
и он работал нормально).
я протестировал JSON против http://jsonlint.com/ и это совершенно справедливо.
что здесь не так?
решение
В поисках ответов на Google, я вернулся к так:json_decode возвращает NULL после в WebService вызов. Мой файл JSON имел последовательность спецификаций UTF (некоторые двоичные символы, которых не должно быть), таким образом, нарушая структуру JSON. Пошел в hex Editor, стер байты. Все вернулось в норму.
Почему это случилось? потому что я отредактировал файл с помощью блокнота Microsoft Windows. ужасная идея!
16 ответов
Это может быть кодировка специальных символов. Вы могли бы спросить json_last_error () чтобы получить определенную информацию.
Update: проблема решена, посмотрите на абзац «решение» в вопросе.
это сработало для меня
json_decode( preg_replace('/[x00-x1Fx80-xFF]/', '', $json_string), true );
48
автор: Dunith Dhanushka
Если вы проверите запрос в chrome, вы увидите, что JSON является текстом, поэтому в JSON добавлен пустой код.
вы можете очистить его с помощью
$k=preg_replace('/s+/', '',$k);
затем вы можете использовать:
json_decode($k)
покажет время.
У меня была та же проблема, и я решил ее, просто заменив символ цитаты перед декодированием.
$json = str_replace('"', '"', $json);
$object = json_decode($json);
мое значение JSON было создано JSON.функция преобразовать в строки.
вы можете попробовать с ним.
json_decode(stripslashes($_POST['data']))
11
автор: Gabriel Castillo Prada
возможно, некоторые скрытые символы возятся с вашим json, попробуйте следующее:
$json = utf8_encode($yourString);
$data = json_decode($json);
$k=preg_replace('/s+/', '',$k);
сделал это для меня. И да, тестирование на Chrome. Thx для user2254008
просто подумал, что добавлю это, поскольку я столкнулся с этой проблемой сегодня. Если есть какие-либо строки заполнения вокруг строки JSON, json_decode вернет NULL.
Если вы вытаскиваете JSON из источника, отличного от переменной PHP, было бы разумно сначала «обрезать»его:
$jsonData = trim($jsonData);
Как указано Jürgen Math, используя метод preg_replace, указанный user2254008, исправил его для меня.
Это не ограничивается Chrome, это, похоже, проблема преобразования набора символов (по крайней мере, в моем случае, Unicode -> UTF8) это исправило все проблемы, которые у меня были.
как будущий узел, объект JSON, который я декодировал, пришел из JSON Python.дампы функционируют. Это, в свою очередь, вызвало некоторые другие антисанитарные данные, чтобы сделать его через, хотя это было легко справиться с.
Если вы получаете json из базы данных, put
mysqli_set_charset($con, "utf8");
после определения соединения link $con
просто сохраните один раз. Я потратил 3 часа, чтобы узнать, что это была просто проблема кодирования html. Попробуйте это
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
1
автор: Samuel Kwame Antwi
это поможет вам понять, какой тип ошибки
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>
1
автор: Krzysztof Przygoda
Я решил эту проблему, распечатав JSON, а затем проверив источник страницы (CTRL / CMD + U):
print_r(file_get_contents($url));
оказалось, что был трейлинг <pre>
тег.
0
автор: Jeffrey Roosendaal
вы должны обеспечить эти пункты
1. ваша строка json не имеет неизвестных символов
2. строка json может просматривать из онлайн-просмотра json (вы можете искать в google как онлайн-просмотрщик или парсер для json), он должен просматривать без каких-либо ошибок
3. ваша строка не имеет HTML-объектов, это должен быть простой текст / строка
для объяснения пункта 3
$html_product_sizes_json=htmlentities($html);
$ProductSizesArr = json_decode($html_product_sizes_json,true);
to (удалить функцию htmlentities ())
$html_product_sizes_json=$html;
$ProductSizesArr = json_decode($html_product_sizes_json,true);
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>