Programing

PHP json_decode ()는 유효한 JSON으로 NULL을 반환합니까?

crosscheck 2020. 8. 25. 07:33
반응형

PHP json_decode ()는 유효한 JSON으로 NULL을 반환합니까?


이 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()작동했습니다).

http://jsonlint.com/ 에 대해 JSON을 테스트 했으며 완벽하게 유효합니다.

여기서 뭐가 잘못 됐나요?

해결책

Google에서 답변을 찾고 SO : json_decode returns NULL after webservice call . 내 JSON 파일에는 UTF BOM 시퀀스 (있을 수없는 일부 이진 문자)가 있으므로 JSON 구조가 손상되었습니다. 16 진수 편집기로 이동하여 바이트를 지 웠습니다. 모든 것이 정상으로 돌아 왔습니다. 왜 이런 일이 일어 났습니까? Microsoft Windows의 메모장을 사용하여 파일을 편집했기 때문입니다. 끔찍한 생각!


It could be the encoding of the special characters. You could ask json_last_error() to get definite information.

Update: The issue is solved, look at the "Solution" paragraph in the question.


This worked for me

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );

You could try with it.

json_decode(stripslashes($_POST['data']))

If you check the the request in chrome you will see that the JSON is text, so there has been blank code added to the JSON.

You can clear it by using

$k=preg_replace('/\s+/', '',$k);

Then you can use:

json_decode($k)

print_r will then show the array.


I had the same problem and I solved it simply by replacing the quote character before decode.

$json = str_replace('"', '"', $json);
$object = json_decode($json);

My JSON value was generated by JSON.stringify function.


Maybe some hidden characters are messing with your json, try this:

$json = utf8_encode($yourString);
$data = json_decode($json);

$k=preg_replace('/\s+/', '',$k); 

did it for me. And yes, testing on Chrome. Thx to user2254008


Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.

If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:

$jsonData = trim($jsonData);

this help you to understand what is the type of error

<?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;
}
?>

As stated by Jürgen Math using the preg_replace method listed by user2254008 fixed it for me as well.

This is not limited to Chrome, it appears to be a character set conversion issue (at least in my case, Unicode -> UTF8) This fixed all the issues i was having.

As a future node, the JSON Object i was decoding came from Python's json.dumps function. This in turn caused some other unsanitary data to make it across though it was easily dealt with.


If you are getting json from database, put

mysqli_set_charset($con, "utf8");

after defining connection link $con


Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this

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);

Here you can find little JSON wrapper with corrective actions that addresses BOM and non-ASCI issue: https://stackoverflow.com/a/43694325/2254935


I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):

print_r(file_get_contents($url));

Turned out there was a trailing <pre> tag.


you should ensure these points

1. your json string dont have any unknowns characters

2. json string can view from online json viewer (you can search on google as online viewer or parser for json) it should view without any error

3. your string dont have html entities it should be plain text/string

for explanation of point 3

$html_product_sizes_json=htmlentities($html);
    $ProductSizesArr = json_decode($html_product_sizes_json,true);

to (remove htmlentities() function )

$html_product_sizes_json=$html;
    $ProductSizesArr = json_decode($html_product_sizes_json,true);

For my case, it's because of the single quotes in the JSON string.

JSON format only accepts double-quotes for keys and string values.

Example:

$jsonString = '{\'hello\': \'PHP\'}'; // valid value should be '{"hello": "PHP"}'
$json = json_decode($jsonString);
print $json; // null

I got this confusing because of Javascript syntax. In Javascript, of course, we can do like this:

let json = {
    hello: 'PHP' // no quote for key, single quote for string value
}

// OR:
json = {
    'hello': 'PHP' // single quote for key and value
}

but later when convert those objects to JSON string:

JSON.stringify(json); // "{"hello":"PHP"}"

<?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>";
?>

참고URL : https://stackoverflow.com/questions/2410342/php-json-decode-returns-null-with-valid-json

반응형