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

如何在JavaScript中从JSON对象中获取id属性值?

JavaScript 提取指定JSON中id字段的实现方案

场景1:已拿到解析完成的JavaScript对象

如果你的接口响应或者其他来源已经把JSON解析为原生JS对象,直接通过点运算符读取即可:

// 示例JS对象
const orderData = {
    "id": "order_I4rOK0TqFk3nxF",
    "entity": "order",
    "amount": 200000,
    "amount_paid": 0,
    "amount_due": 200000,
    "currency": "INR",
    "receipt": "recipt by me",
    "offer_id": null,
    "status": "created",
    "attempts": 0,
    "notes": [],
    "created_at": 1633263345
};
// 提取id
const orderId = orderData.id;
console.log(orderId); // 输出:order_I4rOK0TqFk3nxF

场景2:拿到的是原始JSON字符串

如果拿到的是未解析的字符串格式JSON,需要先调用JSON.parse()方法转为JS对象后再读取:

// 示例JSON字符串
const orderJsonStr = `{
    "id": "order_I4rOK0TqFk3nxF",
    "entity": "order",
    "amount": 200000,
    "amount_paid": 0,
    "amount_due": 200000,
    "currency": "INR",
    "receipt": "recipt by me",
    "offer_id": null,
    "status": "created",
    "attempts": 0,
    "notes": [],
    "created_at": 1633263345
}`;
// 先转成JS对象
const orderData = JSON.parse(orderJsonStr);
// 提取id
const orderId = orderData.id;
console.log(orderId); // 输出:order_I4rOK0TqFk3nxF

兼容提示:如果担心id属性不存在导致报错,可以用可选链操作符做兼容处理:const orderId = orderData?.id;,属性不存在时会返回undefined,不会抛出代码异常

内容的提问来源于stack exchange,提问作者Bhaskar Jyoti Dutta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:36:03