You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中从该JSON数组中获取指定键的值?

从JSON响应中提取特定键的值

以下是几种常用工具/语言的实现方式,按需选择即可:

1. 命令行工具:jq

jq是处理JSON的轻量终端工具,适合直接处理curl返回结果。比如提取所有赛事的Eid:

# 替换<API_URL>为你的接口地址
curl <API_URL> | jq '.Stages[].Events[].Eid'

提取特定赛事的队名(比如首场热身赛的阿富汗队名):

curl <API_URL> | jq '.Stages[0].Events[0].T1[0].Nm'

2. Python

将JSON字符串解析为字典后,通过键路径直接访问:

import json

# 假设curl返回内容已存入response_str变量
response_data = json.loads(response_str)

# 遍历提取所有赛事的Eid
for stage in response_data['Stages']:
    for event in stage['Events']:
        print(event['Eid'])

# 提取特定赛事的状态描述(比如亚运会巴基斯坦vs香港的当前战况)
for stage in response_data['Stages']:
    if stage['Snm'] == "Men's Asian Games Twenty20":
        for event in stage['Events']:
            print(event['ECo'])

3. JavaScript(Node.js环境)

解析JSON后通过层级访问目标值:

const responseData = JSON.parse(responseString); // responseString为curl返回的JSON字符串

// 提取所有赛事阶段的Sid
responseData.Stages.forEach(stage => {
    console.log(stage.Sid);
});

// 提取首场赛事的两队名称
const firstEvent = responseData.Stages[0].Events[0];
console.log(`队1: ${firstEvent.T1[0].Nm}, 队2: ${firstEvent.T2[0].Nm}`);

关键提示

你的JSON是嵌套层级结构:顶级对象 -> Stages数组 -> 单个Stage -> Events数组 -> 单个Event -> T1/T2等子数组,访问时注意数组索引([0]表示第一个元素)和键名大小写(JSON键名区分大小写)。只要对应层级路径,就能精准提取目标键值。

内容的提问来源于stack exchange,提问作者Vishal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 06:57:03