首页 > 解决方案 > 如何解析这种类型的 JSON [PHP]

问题描述

这是下面我要解析的 JSON

{"events": [{"eventId": 2, "payload": {"chat": {"chatId": "683473108@chat.agent", "title": "TrojanTest", "type": "group"}, "from": {"firstName": "Khan", "nick": "Mr.Tr0J4n", "userId": "751401693"}, "msgId": "6895591502924218369", "text": "524545", "timestamp": 1605505008}, "type": "newMessage"}], "ok": true} 我想从这个 JSON中解析msgId和解析。chatId

我怎样才能在 PHP 中做到这一点?

标签: phpjson

解决方案


将 json 字符串解码为数组:

$jsonString = '{"events": [{"eventId": 2, "payload": {"chat": {"chatId": "683473108@chat.agent", "title": "TrojanTest", "type": "group"}, "from": {"firstName": "Khan", "nick": "Mr.Tr0J4n", "userId": "751401693"}, "msgId": "6895591502924218369", "text": "524545", "timestamp": 1605505008}, "type": "newMessage"}], "ok": true}';

$arr = json_decode($jsonString, true);

从数组中获取:

$chatId = $arr['events'][0]['payload']['chat']['chatId'];
$msgId = $arr['events'][0]['payload']['msgId'];
var_dump($chatId);
var_dump($msgId);

结果将是:

string(20) "683473108@chat.agent"
string(19) "6895591502924218369"

推荐阅读