为什么php json_decode无效

时间:2017-05-15 10:50:57

标签: php json

$city_names=json_decode('{"CityList":[{"Id":"1","Name":"Москва","Alias":"msk","Phone":null},{"Id":"2","Name":"Санкт-Петербург","Alias":"spb","Phone":null},{"Id":"4","Name":"Екатеринбург","Alias":"ekb","Phone":null},{"Id":"5","Name":"Новосибирск","Alias":"nsk","Phone":null},{"Id":"6","Name":"Пермь","Alias":"perm","Phone":null},{"Id":"7","Name":"Нижний Новгород","Alias":"nn","Phone":null},{"Id":"8","Name":"Казань","Alias":"kazan","Phone":null},{"Id":"9","Name":"Самара","Alias":"samara","Phone":null},{"Id":"11","Name":"Московская область","Alias":"mo","Phone":null},{"Id":"13","Name":"Уфа","Alias":"ufa","Phone":null},{"Id":"15","Name":"Краснодар","Alias":"krd","Phone":null},{"Id":"17","Name":"Ростов-на-Дону","Alias":"rnd","Phone":null},{"Id":"19","Name":"Челябинск","Alias":"chlb","Phone":null},{"Id":"21","Name":"Воронеж","Alias":"vrn","Phone":null},{"Id":"23","Name":"Ижевск","Alias":"izh","Phone":null}]}',true);

print_r($city_names);

我收到空的。

2 个答案:

答案 0 :(得分:0)

尝试使用json_last_error()来获取错误。

像这样。

$json[] = "{'json': 'MyJson'}";

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 :(得分:-1)

你能试试这个解决方案吗?

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>