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

时间:2016-05-02 13:23:10

标签: php arrays httpresponse

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

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

我想获取详细信息字段值,如何获取它。

4 个答案:

答案 0 :(得分:2)

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



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




答案 1 :(得分:1)

您可以立即阅读响应数组中的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;
?>

答案 2 :(得分:0)

您的数组结构是:

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'];

答案 3 :(得分:0)

(伪)

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

要直接访问(以及编码为JSON)详细信息,您只需使用(类似)以下内容:

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

显然,$response持有相关数组。你的剧本可能有所不同。

然后您将该值分配给变量$detail = $response['errors'][0]->detail;,或者只需输出echo $response['errors'][0]->detail;无论您喜欢什么。