简体   繁体   English

Json_decode不起作用

[英]Json_decode is not working

I can see my json formatted response but once I try to decode and print specific value then it simply goes silent without printing error/null. 我可以看到我的json格式的响应,但是一旦我尝试解码并打印特定值,它就会变得无声而不会输出错误/ null。 tried almost all methods to access json.. Error reporting is on 尝试了几乎所有方法来访问json。错误报告处于启用状态

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true); // without true tried
echo $response; //prints json response
echo $result->count; // does not work here $result['count'] tried

JSON response as below: JSON响应如下:

{"status":200,"message":"data found","data":{"count":"1050"}}

You can do something like this to get individual values, 您可以执行以下操作来获取单个值,

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true);
echo $result['status'] . "<br />";  // 200
echo $result['message'] . "<br />"; // data found
echo $result['data']['count'] . "<br />";  // 1050

Output: 输出:

200
data found
1050

In json_decode() you are telling the function to create an associative array instead of an object by setting the 2nd parameter to true. 在json_decode()中,您通过将2nd参数设置为true来告诉函数创建关联数组而不是对象。 To make it an object just use: 要使其成为对象,只需使用:

$result = json_decode($response);

Otherwise, with your current methodology you can access the variable by using $result['count']; 否则,使用当前的方法,您可以使用$ result ['count'];访问变量。

json_decode function has boolean when TRUE will returned objects will be converted into associative arrays. 当TRUE将返回的对象将转换为关联数组时,json_decode函数具有布尔值。 So if you would like to use objects instead of arrays remove TRUE 因此,如果您想使用对象而不是数组,请删除TRUE

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response);
echo $response; //prints json response
echo $result->count; // should work

or you can use arrays instead of objects 或者您可以使用数组代替对象

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true);
echo $response; //prints json response
echo $result['count'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM