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

如何使用JS从API返回的JSON响应数据中提取指定quote字段值

提取JSON返回值中quote字段的实现方法

JSON解析为JS对象后是通过键名(key)访问对应值的,和两个属性的返回顺序完全无关,只要接口返回的字段名固定为quote,直接访问对应属性即可稳定拿到值。


不同场景的代码实现

  • 已拿到解析后的JS对象
    直接用点语法访问quote属性即可:

    // 例:接口返回的已解析数据
    const apiResult = {
      "quote": "Innovation distinguishes between a leader and a follower.",
      "name": "Steve Jobs"
    };
    // 提取quote值
    const quoteText = apiResult.quote;
    
  • 拿到的是接口返回的原始JSON字符串
    先通过JSON.parse()把字符串转为JS对象,再按上述方式取值:

    // 例:接口返回的未解析原始JSON文本
    const rawResponse = `{"quote":"Innovation distinguishes between a leader and a follower.","name":"Steve Jobs"}`;
    // 转成JS对象
    const apiResult = JSON.parse(rawResponse);
    // 提取quote值
    const quoteText = apiResult.quote;
    

可直接复用的完整请求示例

用原生fetch请求接口时,响应对象自带的.json()方法会自动完成JSON解析,不需要手动调用JSON.parse:

async function getRandomQuote() {
  try {
    // 替换为你实际使用的接口地址
    const res = await fetch('替换为你的接口请求地址');
    // 自动解析JSON返回值为JS对象
    const apiResult = await res.json();
    // 提取quote内容
    const quoteText = apiResult.quote;

    // 后续业务逻辑直接使用quoteText即可
    console.log(quoteText);
    return quoteText;
  } catch (err) {
    console.error('接口请求/解析异常:', err);
  }
}

// 调用函数即可每次拿到随机返回的quote内容
getRandomQuote();

补充说明:不需要在意接口每次返回quote、name两个字段的排列顺序,JS对象的键值访问逻辑和属性书写顺序没有关联,只要字段名quote不发生变更,上述写法就可以稳定运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:42:32