php 响应体为对象数组,如何解析内容

php response body as object array, how to parse the content

其中一个 API return 响应作为对象数组,我 json 将对象数组编码如下

{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"MISSING_REQUIRED_PARAMETER","detail":"Missing required parameter.","field":"amount_money.amount"}]}

我想获取detail字段值,如何获取。

使用点符号访问对象元素:

     // if that response is as string JSON
    var obj = JSON.parse('{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"MISSING_REQUIRED_PARAMETER","detail":"Missing required parameter.","field":"amount_money.amount"}]}');

    alert("Details is: "+obj.errors[0].detail);

您可以立即从响应数组读取 detail 字段。

<?php
$json = '{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"MISSING_REQUIRED_PARAMETER","detail":"Missing required parameter.","field":"amount_money.amount"}]}';

我正在将您的 JSON 转换为 Array 只是为了举例。

//Actual Array Response
$a = json_decode($json, true);

echo "<pre>";
print_r($a);
echo "</pre>";

//Save detail to Variable
$detail = $a['errors'][0]['detail'];
echo $detail;
?>

你的数组结构是:

array (size=1)
  'errors' => 
    array (size=1)
      0 => 
        array (size=4)
          'category' => string 'INVALID_REQUEST_ERROR' (length=21)
          'code' => string 'MISSING_REQUIRED_PARAMETER' (length=26)
          'detail' => string 'Missing required parameter.' (length=27)
          'field' => string 'amount_money.amount' (length=19)

因此,要深入了解,您可以这样获取:

$array = json_decode('{"errors":[{"category":"INVALID_REQUEST_ERROR","code":"MISSING_REQUIRED_PARAMETER","detail":"Missing required parameter.","field":"amount_money.amount"}]}',true);    
echo $array['errors'][0]['detail'];

(伪)

$response = Array (
    [errors] => Array (
        [0] => stdClass Object (
            [category] => INVALID_REQUEST_ERROR
            [code] => MISSING_REQUIRED_PARAMETER
            [detail] => Missing required parameter.
            [field] => amount_money.amount
        )
    )
)

要直接访问(并且编码为JSON)detail,您只需使用(类似于)以下内容:

$response['errors'][0]->detail

很明显,$response 所在的位置是有问题的数组。您的脚本可能有所不同。

然后你将该值赋给一个变量$detail = $response['errors'][0]->detail;,或者简单地输出它echo $response['errors'][0]->detail;任何你喜欢的。