我有一个来自API的JSON响应,格式如下:
string(2228) "{"question":{"type":"single","text":"Have you noticed any insects on you or have you been bitten by any insect (lice, mosquitoes, ticks, bedbugs, etc.)?",
"items":
[
{"id":"p_48","name":"Insect bite","
choices":
[{"id":"present","label":"Yes"},
{"id":"absent","label":"No"},
{"id":"unknown","label":"Don't know"}
]}
],
"extras":{}
},
"conditions":[
{"id":"c_87","name":"Common cold","common_name":"Common cold","probability":0.028},
{"id":"c_10","name":"Gastroenteritis","common_name":"Gastroenteritis","probability":0.0238},
{"id":"c_49","name":"Migraine","common_name":"Migraine","probability":0.0096}
],
"extras":{},"should_stop":false}"
我需要得到问题 - >文字,
ID和选择
&安培;&安培; 具有ID,名称和概率的条件。
我尝试了以下内容:
<?php
$str = file_get_contents("test.json");
//var_dump($str);
$json = json_decode($str, true);
echo '<pre>' . print_r($json, true) . '</pre>';
?>
没有输出。我也尝试了如下的PHP RecursiveArrayIterator:
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
并收到以下错误消息:
Passed variable is not an array or object
我是php新手,无法理解原因??帮助专家征求意见。
更新
我直接从终端调用了CURL,发现它缺少string(2228) "
和尾随"
部分。所以我确实爆炸了。由于它是一个多维数组的数组,我做了递归数组迭代器,如下所示:
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($str, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
转到所需的输出。问题已解决。
答案 0 :(得分:1)
尝试在测试文件中复制此代码,然后获得结果:
这是JSON语法中的错误:
"name": "Insect bite",
"
choices "
尝试下面的代码示例
{
"question": {
"type": "single",
"text": "Have you noticed any insects on you or have you been bitten by any insect (lice, mosquitoes, ticks, bedbugs, etc.)?",
"items": [{
"id": "p_48",
"name": "Insect bite",
"choices": [{
"id": "present",
"label": "Yes"
},
{
"id": "absent",
"label": "No"
},
{
"id": "unknown",
"label": "Don't know"
}
]
}],
"extras": {}
},
"conditions": [{
"id": "c_87",
"name": "Common cold",
"common_name": "Common cold",
"probability": 0.028
},
{
"id": "c_10",
"name": "Gastroenteritis",
"common_name": "Gastroenteritis",
"probability": 0.0238
},
{
"id": "c_49",
"name": "Migraine",
"common_name": "Migraine",
"probability": 0.0096
}
],
"extras": {},
"should_stop": false
}
答案 1 :(得分:0)
希望这会对你有帮助,看到这里我可以访问你的json属性
<?php
$str = file_get_contents("https://api.myjson.com/bins/7gc8n");
$json = json_decode($str, true);
// checkout this I am getting json here
echo '<pre>';
// print_r($json, true);
print_r($json['question']['text']);
print_r($json['conditions']);
echo '</pre>';
?>