如何在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
相关产品推荐
相关产品推荐

