首页 > 解决方案 > 如何解码来自 API 的 json 响应

问题描述

我从这样的 API 调用数据:

$curl = curl_init();
//adding fields to the curl object to enter the site
curl_setopt($curl, CURLOPT_URL, $my_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);  
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);

//executing the curl call and getting data back
$jsonStr = curl_exec($curl);

curl_close($curl); // close the connection

print_r($jsonStr);

它工作正常,但问题是我无法解码 json 响应。我得到这样的东西:

[{"id":1,"name":"Books","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"200.0000"}],"tax":[]},{"id":2,"name":"pencil","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"5000.0000"}],"tax":[]}]

我试图解码它并调用像“echo $code[0]['name'];”这样的值 我不能,它显示了相同的 json 数组,然后我尝试将 json 数组保存到一个变量中,例如:

$json = '[{"id":1,"name":"Books","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"200.0000"}],"tax":[]},{"id":2,"name":"pencil","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"5000.0000"}],"tax":[]}]';

并尝试对其进行解码并且它有效,我认为问题出在单引号上。我不确定,但这是我根据我得到的结果所假设的。我是 curl、json 和 php 的新手,所以如果有人可以帮助我。

顺便说一句,我正在尝试这样解码:

$code = json_decode($jsonStr ,true);
echo $code[0]['id'];

但它不起作用,它返回相同的完整 json 数组,而不是我试图获取的值

当我试图回显 $jsonStr 时,我得到:

[{"id":1,"name":"Books","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"200.0000"}],"tax":[]},{"id":2,"name":"pencil","description":null,"reference":null,"status":"active","category":{"id":"5048","name":"Ventas"},"price":[{"idPriceList":"1","name":"General","type":"amount","price":"5000.0000"}],"tax":[]}]

标签: phparraysjsoncurl

解决方案


您可以使用 json_decode() 方法

请参考此链接http://php.net/manual/en/function.json-decode.php


推荐阅读