Ошибка json error syntax error 4

Перейти к контенту

При настройке сайта, пункт «Рабочий стол — Маркетинг — Поисковая оптимизация — Поисковые системы — Яндекс» при попытке авторизоваться через Яндекс и вводе полученного от Яндекс кода подтверждения получаю «Не удалось получить авторизацию: JSON error: Syntax error [4]». Причем данная ошибка видна только в Mozilla Firefox, в других браузерах просто не происходит авторизации. Битрикс установлен в виртуальной машине от разработчика (Bitrix virtual appliance version 7.4.3).

Обратился в ТП битрикса, неделю переписывался, попросили доступы не только в админку сайта но и доступы к аккаунту Яндекса (зачем?). После недельной переписки с ТП выяснилось, что есть проблема с подключением к сайту именно Яндекса.

Проверить проблему подключения к «oauth.yandex.ru» можно кодом:

$res = stream_socket_client(«ssl://oauth.yandex.ru:443», $errno, $errstr, 5);
var_dump($res);

И проблема была из-за того, что виртуалка была создана на CentOS 6.10, в которой для корректной работы с сервисами Яндекса необходимо принудительно обновить CA.

Делается следующим образом:

update-ca-trust enable

На всякий случай скопировали текущие CA (могут быть по другому пути):

cp /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem tls-ca-bundle.pem

Скачали новые и обновили CA.

curl https://www.certum.pl/CA.pem > /etc/pki/ca-trust/source/anchors/certum_pl_CA.pem
update-ca-trust extract

После этого вышеприведенный код перестал выдавать ошибку при подключении к сайту Яндекса.


UPDATE: FINAL SOLUTION

It turned out to be invisible characters afterall. Which characters exactly? I couldn’t tell you.

Here is a 1-liner that fixed the problem:

<?php
// get string from $_POST, 
// wp_unslash it, 
// then sanitize as text, 
// then json_decode, 
// and assign to variable as assoc. array ready for action
$location = json_decode(sanitize_text_field(wp_unslash($_POST['acf']['field_621fa9e5511f3'])), true);

// These are the default sanitization functions used when update_post_meta is fired. 
// By default they:
//   * Check for invalid UTF-8 (uses wp_check_invalid_utf8())
//   * Converts single < characters to entity
//   * Strips all tags
//   * Remove line breaks, tabs and extra white space
//   * Strip octets
?>

One or more of those things was causing the issue. It didn’t seem like I needed to strip any invisible/special chars, but turns out I did.

NOTE:
None of these had any effect. The built-in WP functions above finally did the trick!

<?php
trim($_POST['acf']['field_621fa9e5511f3'])

urlencode($_POST['acf']['field_621fa9e5511f3'])

str_replace(array("r", "n"), "", $_POST['acf']['field_621fa9e5511f3']);
?>

UPDATE

To get right to the issue at hand, it seems json_decode is not working when I pass it the $location string variable (with $_POST as the source), but works fine using the string itself (which validates fine on https://jsonlint.com and as @CBroe posted at https://3v4l.org/FSDnf)

<?php 

global $_POST;

$location = $_POST['acf']['field_621fa9e5511f3'];

// var type
echo gettype($location); 
// returns: string

// var_dump
var_dump($location); 
// returns: string(375) "{"lat":27.884301199999999,"lng":-82.389221199999994,"zoom":14,"markers":[{"label":"Burts Road 6311, 33619 Tampa, Florida United States","default_label":"Burts Road 6311, 33619 Tampa, Florida United States","lat":27.884189800000001,"lng":-82.389353099999994}],"address":"Burts Road 6311, 33619 Tampa, Florida United States","layers":["OpenStreetMap.Mapnik"],"version":"1.3.2"}"

// echo string
echo $location; 
// returns: {"lat":27.884301199999999,"lng":-82.389221199999994,"zoom":14,"markers":[{"label":"Burts Road 6311, 33619 Tampa, Florida United States","default_label":"Burts Road 6311, 33619 Tampa, Florida United States","lat":27.884189800000001,"lng":-82.389353099999994}],"address":"Burts Road 6311, 33619 Tampa, Florida United States","layers":["OpenStreetMap.Mapnik"],"version":"1.3.2"} 

// json_decode string as a variable
var_dump(json_decode($location, true), json_last_error());
// fails with error 4 for syntax

// json_decode string itself
var_dump(json_decode('{"lat":27.884301199999999,"lng":-82.389221199999994,"zoom":14,"markers":[{"label":"Burts Road 6311, 33619 Tampa, Florida United States","default_label":"Burts Road 6311, 33619 Tampa, Florida United States","lat":27.884189800000001,"lng":-82.389353099999994}],"address":"Burts Road 6311, 33619 Tampa, Florida United States","layers":["OpenStreetMap.Mapnik"],"version":"1.3.2"}', true), json_last_error());
// works fine

?>

Something about the $_POST data source/type because setting the string manually works fine:

// set string variable
$location = '{"lat":27.884301199999999,"lng":-82.389221199999994,"zoom":14,"markers":[{"label":"Burts Road 6311, 33619 Tampa, Florida United States","default_label":"Burts Road 6311, 33619 Tampa, Florida United States","lat":27.884189800000001,"lng":-82.389353099999994}],"address":"Burts Road 6311, 33619 Tampa, Florida United States","layers":["OpenStreetMap.Mapnik"],"version":"1.3.2"}';

//  var_dump json_decode
var_dump(json_decode($location, true), json_last_error()); 
// works fine

I’m not sure where «the break» exists. From everything I can see this should work fine, but it doesn’t:

<?php
global $_POST;

// get string from $_POST, json_decode() it, and then var_dump
var_dump(json_decode($_POST['acf']['field_621fa9e5511f3'], true), json_last_error());
// fails with error 4 for syntax
?>

ORIGINAL POST BELOW

Lots of other topics with a similar problem, but none of the solutions have worked for me.

I have VALID JSON data that I grab from $_POST when a WordPress custom post_type is added/updated. The purpose is to use some of the JSON data for other specific custom fields on each save. Here is some example JSON data grabbed:

{
    "lat":27.884301199999999,
    "lng":-82.389221199999994,
    "zoom":12,
    "markers":[
        {
            "label":"Burts Road 6311, 33619 Tampa, Florida United States",
            "default_label":"Burts Road 6311, 33619 Tampa, Florida United States",
            "lat":27.884189800000001,
            "lng":-82.389353099999994
        }
    ],
    "address":"Burts Road 6311, 33619 Tampa, Florida United States",
    "layers":["OpenStreetMap.Mapnik"],
    "version":"1.3.2"
}

It validates perfectly fine at https://jsonlint.com

When I try decode it, json_last_error() shows «4» for «JSON_ERROR_SYNTAX». The relevant code in my function looks like this:

<?php
    global $_POST;
        
    // get JSON data from $_POST
    $location = $_POST['acf']['field_621fa9e5511f3']

    /* Example JSON data for "$location" is shown above */
      
    // get assoc. array from JSON
    $location_decode = json_decode( $location, true );
     
    /* here's where my custom code would go to do all of my processing */
     
    // add/update values to post_meta table after all processing
    update_post_meta( $post_id, 'JSON_Decoded', $location_decode );
    update_post_meta( $post_id, 'JSON_Last_error', json_last_error() );
?>

«$location_decode» is always empty (which means the ‘JSON_Decoded’ meta field is also always empty).

var_dump of $location

string(375) "{"lat":27.884301199999999,"lng":-82.389221199999994,"zoom":14,"markers":[{"label":"Burts Road 6311, 33619 Tampa, Florida United States","default_label":"Burts Road 6311, 33619 Tampa, Florida United States","lat":27.884189800000001,"lng":-82.389353099999994}],"address":"Burts Road 6311, 33619 Tampa, Florida United States","layers":["OpenStreetMap.Mapnik"],"version":"1.3.2"}" 

Solutions Tried:

I tried removing some of the invisible special characters like BOM, but since the source of the data is $_POST and not a file, these kind of invisible characters shouldn’t really matter:

<?php
    if (0 === strpos(bin2hex($location), 'efbbbf')) {
        $location = substr($location, 3);
    }
?>

I tried setting encoding to UTF8 prior to JSON decode, even though the UTF8 is the default encoding for the site and DB. 2 methods tried, and both had no effect:

<?php
    // method #1
    $location = utf8_encode($_POST['acf']['field_621fa9e5511f3']);

    // method #2
    $location = mb_convert_encoding($_POST['acf']['field_621fa9e5511f3'], "UTF-8", "UTF-8"); 
?>

I’ve been messing with it for hours and now I’m reaching out for help out of frustration.

What is wrong with the sample JSON data syntax and/or how can I get it to pass JSON_decode’s syntax checks?

I had previously asked the same question. I would like to decode the json from: http://pad.skyozora.com/data/pets.json. Below is the code I used previously:

<?php
$html=file_get_contents("http://pad.skyozora.com/data/pets.json");
var_dump(json_decode($html,true)); //return null
var_dump(json_last_error()); // return 4
?>

From the last answer I know there is UTF8 DOM in the json return. I tried the answer from a similar question: json_decode returns NULL after webservice call, but all of the answers not work for me.

And after do more research I found a way that works:

<?php
$html=file_get_contents("http://pad.skyozora.com/data/pets.json");
$html=preg_replace('/[x00-x1Fx80-xFF]/', '', $html);
var_dump(json_decode($html, true));
var_dump(json_last_error());
?>

This successfully decode the json into array. However all Chinese and Japanese character string were removed too. Any ideas?

Edited:

I used http://jsonlint.com/ to decode the json from http://pad.skyozora.com/data/pets.json. It stops at here:

[
            161,
            "進化的紅面具",
            0,
            -1,
            0,
        -1,
        1,
        1,
        10,
        50,
        1,
        0,
        0,
        0,
        0,
        [

        ],
        [
            0,
            0,
            0,
            0,
            0,
            0,
            0
        ],
        "http://i.imgur.com/Y1jZlGW.png",
        [
            "ウルカヌ火山",
            "メジェド

and give me the error:

Parse error on line 5001:
...山",                "メジェド
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

But I couldn’t see any problem with this part of json.

Just downloaded TasmoAdmin from Github (v1.6.1 xampp portable for Win) and installed. Didn’t find any Tasmota devices with auto-scan (2 currently online, can http to them), so I tried to add them manually. The first one got the following error:

Device not found

JSON ERROR => 4: Syntax error
Please copy the whole error message and copy it in a new issue on GitHub. Somehow the Tasmota Firmware answered a wrong formatted JSON string which needs to get adjusted in TasmoAdmin.
JSON Answer => {«Status»:{«Module»:18,»FriendlyName»:[«KMTA_F1_L03″],»Topic»:»KMTA_F1_L03″,»ButtonTopic»:»0″,»Power»:0,»PowerOnState»:3,»LedState»:1,»SaveData»:1,»SaveState»:1,»ButtonRetain»:0,»PowerRetain»:0},»StatusPRM»:{«Baudrate»:115200,»GroupTopic»:»sonoffs»,»OtaUrl»:»http://sonoff.maddox.co.uk/tasmota/sonoff.bin»,»RestartReason»:»Hardware Watchdog»,»Uptime»:»24T05:33:15″,»StartupUTC»:»2019-10-11T09:56:33″,»Sleep»:0,»BootCount»:44,»SaveCount»:61,»SaveAddress»:»F9000″},»StatusFWR»:{«Version»:»6.2.1″,»BuildDateTime»:»2018-09-09T16:49:54″,»Boot»:31,»Core»:»2_3_0″,»SDK»:»1.5.3(aec24ac9)»},»StatusLOG»:{«SerialLog»:2,»WebLog»:2,»SysLog»:0,»LogHost»:»»,»LogPort»:514,»SSId»:[«ATT696″,»ATT696″],»TelePeriod»:60,»SetOption»:[«00008309″,»55818000″,»00000000″]},»StatusMEM»:{«ProgramSize»:494,»Free»:508,»Heap»:14,»ProgramFlashSize»:1024,»FlashSize»:1024,»FlashMode»:3,»Features»:[«00000809″,»0FDEE794″,»000003A4″,»37FFBFCE»,»00000000″]},»StatusNET»:{«Hostname»:»KMTA_F1_L03-2528″,»IPAddress»:»192.168.1.175″,»Gateway»:»192.168.1.254″,»Subnetmask»:»255.255.255.0″,»DNSServer»:»192.168.1.254″,»Mac»:»80:7D:3A:4D:A9:E0″,»Webserver»:2,»WifiConfig»:5},»StatusMQT»:{«MqttHost»:»192.168.1.250″,»MqttPort»:1883,»MqttClientMask»:»DVES_%06X»,»MqttClient»:»DVES_4DA9E0″,»MqttUser»:»»,»MqttType»:1,»MAX_PACKET_SIZE»:1000,»KEEPALIVE»:15},»StatusTIM»:{«UTC»:»Mon Nov 04 15:29:48 2019″,»Local»:»Mon Nov 04 16:29:48 2019″,»StartDST»:»Sun Mar 31 02:00:00 2019″,»EndDST»:»Sun Oct 27 03:00:00 2019″,»Timezone»:1,»Sunrise»:»07:41″,»Sunset»:»17:25″},»StatusSNS»:{«Time»:»2019-11-04T16:29:48″,»AM2301″:{«Temperature»:nan,»Humidity»:nan},»TempUnit»:»F»},»StatusSTS»:{«Time»:»2019-11-04T16:29:48″,»Uptime»:»24T05:33:15″,»Vcc»:3.190,»Wifi»:{«AP»:1,»SSId»:»ATT696″,»RSSI»:54,»APMac»:»20:E5:64:09:68:20″}}}

The other tasmota device added successfully (also manually) and can be manipulated by TasmoAdmin.

Tried to add the error device again and never got an option for manual add, and the AutoScan does not find it.

Error description

In the PHP development process, when processing json strings, json_decode returns NULL, calling last_error returns 4 (JSON_ERROR_SYNTAX), but json strings can be correctly processed by other languages ​​such as python, javascript or some online json parsers.

Diagnosis

There are several situations that generally cause php json_decode errors here:

1. The json string is read from a file and the character order mark (BOM) is not removed

2. json contains invisible characters, json_decode parsing errors

3. json object value is a single-quoted string

In particular, the third error is relatively hidden, the naked eye is often easy to ignore

Solution:

The following solutions are given for the above three cases

1.BOM Issue:

Open the file in binary mode and confirm whether there is a BOM. If so, remove the BOM before parsing. The following code takes UTF-8 as an example to detect and delete BOM.

function removeBOM($data) {

if (0 === strpos(bin2hex($data), ‘efbbbf’)) {

return substr($data, 3);

}

return $data;

}

2.Invisible character

Remove invisible characters before parsing.

for ($i = 0; $i <= 31; ++$i) {

$s = str_ replace(chr($i), “”, $s);

}

3.Single quote string value

Let’s look at the following example:

<?php

$s = “{”x”:’abcde’}”;

$j = json_ decode($s, true);

var_ dump($j);

echo json_ last_ error() . “n”;

PHP 5.5. 9 output

NULL

four

Generally, you only need to replace single quotation marks with double quotation marks. During specific processing, you should pay attention to that single quotation marks may also appear in other places. Whether to replace them globally needs to be analyzed according to the specific situation.

Read More:

Понравилась статья? Поделить с друзьями:
  • Ошибка js движка uncaught invalid json
  • Ошибка jpg невозможен просмотр
  • Ошибка kernell dll
  • Ошибка kernel thread priority floor violation
  • Ошибка kernel task