请问我如何解析这个 json 响应:
{ "info": { "apiVersion": "1.1", "clientFeatures": ["all"], "clientTime": "2014-11-27T23:04:27.542Z", "emotions": [], "input": "who+created+you", "isNewUser": true, "locale": "en", "location": "53.0%2C9.0", "login": "mashape", "responseTime": 948 }, "output": [{ "actions": { "custom": {}, "say": {"text": "I was created by the cool guys from Pannous."} }, "entities": { "dialoguesInfo": { "dialog": "Sandbox", "dialog_id": "63", "forced": false, "initiative": false, "match_id": "205233", "matchscore": "3.77", "response_id": "205224" }, "input": "who+created+you", "locale": "en" }, "responseTime": 673, "results": {} }] }
我想得到结果:输出>操作>说。
我已经试过了:$req = $response -> raw_body; foreach($req as $ob->$val){}
但不起作用。
我也试过json_decode
但没有工作。
正如Tomasz Kowalczyk在这样做时已经建议的那样,json_decode
是一个很好的本机函数。
有时,当代码没有按照您期望的方式工作时,可能会令人沮丧,但人们确实在努力提供帮助。当某些东西没有按照你想要的方式工作时,请确保包括它对你不起作用的方式。
$x = '{ "info": { "apiVersion": "1.1", "clientFeatures": ["all"], "clientTime": "2014-11-27T23:04:27.542Z", "emotions": [], "input": "who+created+you", "isNewUser": true, "locale": "en", "location": "53.0%2C9.0", "login": "mashape", "responseTime": 948 }, "output": [{ "actions": { "custom": {}, "say": {"text": "I was created by the cool guys from Pannous."} }, "entities": { "dialoguesInfo": { "dialog": "Sandbox", "dialog_id": "63", "forced": false, "initiative": false, "match_id": "205233", "matchscore": "3.77", "response_id": "205224" }, "input": "who+created+you", "locale": "en" }, "responseTime": 673, "results": {} }] }';
比json_decode
和var_dump
查看输出。
var_dump(json_decode($x));
结果:
class stdClass#1 (2) {
public $info =>
class stdClass#2 (10) {
public $apiVersion =>
string(3) "1.1"
public $clientFeatures =>
array(1) {
[0] =>
string(3) "all"
}
public $clientTime =>
string(24) "2014-11-27T23:04:27.542Z"
public $emotions =>
array(0) {
}
public $input =>
string(15) "who+created+you"
public $isNewUser =>
bool(true)
public $locale =>
string(2) "en"
public $location =>
string(10) "53.0%2C9.0"
public $login =>
string(7) "mashape"
public $responseTime =>
int(948)
}
public $output =>
array(1) {
[0] =>
class stdClass#3 (4) {
public $actions =>
class stdClass#4 (2) {
...
}
public $entities =>
class stdClass#7 (3) {
...
}
public $responseTime =>
int(673)
public $results =>
class stdClass#9 (0) {
...
}
}
}
}
如您所见,json_decode
工作正常。对于完整的夏季数据,而不是 var_dump
,完全按照上述操作,但使用 print_r
。
请记住,如果您希望将解码的数据作为数组,请使用json_decode($yourData, true)
从这里开始,现在应该非常清楚,如何访问您想要的数据。如果没有,不用担心,解决方案已经接近了,只需写一条评论,说明哪些部分让您感到困惑。
剧情透露
我在这里为您添加了小片段 https://eval.in/227351基本上,0 偏移量是让您感到困难的原因......
$foo = json_decode($x, TRUE);
var_dump($foo['output'][0]['actions']);