Json到php数组(Json_decode())不工作
我进行了一个API调用,并尝试将json响应转换为php数组。但是,当使用is_数组函数进行检查时,发现它不是数组 调用ApiJson到php数组(Json_decode())不工作,php,json,Php,Json,我进行了一个API调用,并尝试将json响应转换为php数组。但是,当使用is_数组函数进行检查时,发现它不是数组 调用Api $ch = curl_init("https://api.url.com/value/value"); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , "token")); $result = curl_exec($ch); curl_close($ch); $r
$ch = curl_init("https://api.url.com/value/value");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , "token"));
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
API调用返回的Json:
[
{
"number":"65",
"Field":"test",
"Name":"test",
"type":"Numeric",
"MaximumLength":128,
"MinimumLength":0,
"Options":"required"
}
]
等等
我使用
json_decode($result);
但是像这样检查,
if (is_array($result)) {
echo "is array";
} else {
echo "is not an array!";
}
回声“不是数组”
我检查了json响应,它是有效的json代码。
我也试过了
json_decode($result, true);
同样的结果
我是否犯了一些明显的错误?您可以使用
json\u last\u error()
和json\u last\u error\u msg()
查看您试图解析的json有什么问题。我通常使用json_decode的以下包装,当解码失败时抛出异常:
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return mixed
* @throws \InvalidArgumentException if the JSON cannot be decoded.
* @link http://www.php.net/manual/en/function.json-decode.php
*/
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
'json_decode error: ' . json_last_error_msg());
}
return $data;
}
以下代码片段的行为似乎与预期一致(回音1),因此您的JSON是有效的,可以正常工作
$result = '[{"ConditionCode":"1","Field":"test","Name":"test","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"required"}]';
$x = json_decode($result, true);
echo($x[0]["ConditionCode"]);
我猜你刚刚在$result上运行了json_解码?json_decode不会设置将其馈送到json解码数组的变量的值。它只是返回数组,因此您必须将该值分配给另一个变量(在本例中为该变量本身)
试一试
而不是
json_decode($result, true);
json响应似乎是incomplete@ka_lin我编辑了这个问题,所以它是正确的。我把它缩短了,以便不用json把整个问题串起来。检查json是否正确时,Jsonlint返回“valid”。尝试使用
is_object
而不是is_array
@MouradKaroudi刚刚尝试过,结果相同。$result=json_decode($result)代码>解码后是否重新分配新元素。工作正常<代码>http://sandbox.onlinephpfunctions.com/code/149cc2763575f18bac9dc669afc11ea3cc26b8d3
在将$result传递给解码函数之前,它是一个字符串吗?我会重新分配它。我尝试了这两种方法,$result=json_decode($result,true);$result=json_decode($result);(没有(,true)。但是我得到了相同的结果。回显$result是否完全符合您的期望?尝试回显gettype($result)以检查其类型。在运行解码之前和之后都在$result上尝试。回显$result返回1
,而gettype返回布尔值
json_decode($result, true);