【已解决】PHP中处理JSON字符串

【背景】

折腾:

【已解决】安全模式下实现微信添加自定义菜单

期间,需要去先处理好返回的JSON字符串:

{"access_token":"f_FvmMYUVcjEDcy2-qjduh51ffm9h0cqxDBgYVo6JtCBApbtWGnq9GMIsLoh-tVj5R-8Mq-S7ALaxSeY8qzv1tSAGusP8nFq3Eh1Y-1qzkE","expires_in":7200}

变成对象,以便后续操作。

 

【折腾过程】

1.搜:

php json process

参考:

How to process JSON in PHP? – Stack Overflow

Parsing JSON file with PHP – Stack Overflow

去试试

PHP: json_decode – Manual

试试代码:

$decodedJsonObj = json_decode($respJson);
var_dump($decodedJsonObj);
$decodedJsonArr = json_decode($respJson, true);
var_dump($decodedJsonArr);

输出结果是:

object(stdClass)#2 (2) {
  ["access_token"]=>
  string(107) "sKTUQsuAw3bd5W79DZTF9xuycUGBZM6sGZzDYETegpq_eHsJedYgiIpREdcaqL-1FSlhn16aWtGxr9Vaj7FJk3z-PjmgRaaFidsv9VHh-50"
  ["expires_in"]=>
  int(7200)
}
array(2) {
  ["access_token"]=>
  string(107) "sKTUQsuAw3bd5W79DZTF9xuycUGBZM6sGZzDYETegpq_eHsJedYgiIpREdcaqL-1FSlhn16aWtGxr9Vaj7FJk3z-PjmgRaaFidsv9VHh-50"
  ["expires_in"]=>
  int(7200)
}

2.然后去判断json对象中是否包含某个key:access_token

【已解决】PHP中如何判断JSON对象或JSON数组中包含某个key键值

 

【总结】

正常处理json的方式,其实很简单,就是编码和解码。

此处用到了解码:

$decodedJsonObj = json_decode($respJson);

或:

$decodedJsonArr = json_decode($respJson, true);

接着,此处通过去判断是否包含对应键值,知道是否出错:

// $decodedJsonObj = json_decode($respJson);
$decodedJsonArr = json_decode($respJson, true);
$crifanLib->logWrite("decodedJsonArr=%s", $decodedJsonArr);
if(array_key_exists("access_token", $decodedJsonArr)){
    $access_token = $decodedJsonArr['access_token'];
    $crifanLib->logWrite("access_token=%s", $access_token);
}
else{
    $crifanLib->logWrite("Error while get access token: errcode=%d, errmsg=%s", $decodedJsonArr['errcode'], $decodedJsonArr['errmsg']);
}

万一json解码出错,也可以通过:

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

去得知错误原因。



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量