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

Node.js中动态定位API返回JSON的指定类型价格数据

在Node.js中根据动态标识定位并提取JSON数组中的商品价格

由于API返回的JSON数组元素顺序不固定,无法依赖索引定位价格元素,我们可以通过数组遍历方法,根据atom.type === 'price'的标识精准匹配目标元素,再提取价格值。

核心实现代码

// 从API获取的JSON数组(示例结构)
const jsonFromApi = [
  {
    type: 'atom',
    id: 'atom',
    atom: { type: 'priceWithTitle', priceWithTitle: {} }
  },
  {
    type: 'atom',
    id: 'atom',
    atom: { type: 'price', price: { value: 99.9, currency: 'CNY' } }
  },
  {
    type: 'atom',
    id: 'name',
    atom: { type: 'textAtom', textAtom: {} }
  },
  { atom: { type: 'labelList', labelList: {} } }
];

// 定位第一个符合条件的价格元素
const priceElement = jsonFromApi.find(item => {
  // 先校验元素是否存在atom属性,避免运行报错
  if (!item?.atom) return false;
  // 匹配atom类型为'price'的元素
  return item.atom.type === 'price';
});

// 提取并使用价格值
if (priceElement) {
  // 根据API返回的真实price对象结构调整字段名
  const { value, currency } = priceElement.atom.price;
  console.log(`商品价格:${value} ${currency}`); // 输出:商品价格:99.9 CNY
} else {
  console.log("未找到有效的价格元素");
}

关键说明

  1. 使用Array.find():该方法会遍历数组,返回第一个满足匹配条件的元素,刚好适配“只需要一个价格元素”的场景。
  2. 空值校验:通过item?.atom(可选链操作符)判断元素是否包含atom属性,避免因数组中存在结构不一致的元素导致报错。
  3. 灵活适配结构:提取价格时,需要根据API返回的price对象真实结构调整字段(比如有的可能是price.amount而非price.value)。

处理多个价格元素的场景

如果API可能返回多个type: 'price'的元素,可以改用Array.filter()获取所有匹配元素,再遍历处理:

const allPriceElements = jsonFromApi.filter(item => {
  if (!item?.atom) return false;
  return item.atom.type === 'price';
});

allPriceElements.forEach(elem => {
  const priceInfo = elem.atom.price;
  console.log(`价格:${priceInfo.value} ${priceInfo.currency}`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:50:36