php - 如何解码来自 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":[]}]
解决方案
您可以使用 json_decode() 方法
推荐阅读
- java - LED 闪光灯在 Oreo O 8.0 及更高版本中不工作,而在以下所有操作系统版本中工作
- c++ - 为什么我的代码在 Visual Studio 中不起作用?
- excel - Excel:AVERAGEIFS 链接成对的标准,但不工作
- mysql - 将 NodeJS Docker 容器连接到 MySQL Docker 容器 - docker-compose 3
- reactjs - React Material-UI not justify-content 不适用于我的所有卡片
- java - 如何将 MainActivity 中的值添加到 SecondActivity 中的列表
- c - 服务器仅向第一个客户端广播
- ffmpeg - 如何使用 ffmpeg hwaccel d3d11va 解码?
- reactjs - 为什么我的 React/JSX if 语句仍在执行?
- twig - 侧边栏区域内容显示在 drupal 8 的主要内容下方