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

JavaScript/Node.js读取外部JSON文件并统计指定属性值的出现次数

前置修正说明

首先你提供的示例metadata.json格式不符合标准JSON规范,多个独立对象需要包裹为数组,否则会触发JSON.parse报错,修正后正确的文件结构如下:

[
  {
    "name": "#1",
    "attributes": [
      {
        "trait_type": "Background",
        "value": "Neon"
      },
      {
        "trait_type": "Color",
        "value": "Red"
      }
    ]
  },
  {
    "name": "#2",
    "attributes": [
      {
        "trait_type": "Background",
        "value": "Neon"
      },
      {
        "trait_type": "Color",
        "value": "Red"
      }
    ]
  }
]

其次你原有代码存在冗余逻辑:异步fs.readFile的回调中不需要再重复调用同步fs.readFileSync读取文件,前者已经拿到了完整的文件内容。

完整实现代码
const fs = require("fs");
const path = require("path");
const isLocal = typeof process.pkg === "undefined";
const basePath = isLocal ? process.cwd() : path.dirname(process.execPath);

// 定义要统计的目标参数,可按需修改
const TARGET_TRAIT_TYPE = "Background";
const TARGET_VALUE = "Neon";
let count = 0;

fs.readFile(`${basePath}/build/json/metadata.json`, 'utf8', function(err, contents) {
    if (err) {
      console.log('Error reading file: ', err);
      return;
    }
    try {
      const data = JSON.parse(contents);
      // 遍历每个元数据条目
      data.forEach(item => {
        // 筛选匹配trait_type的属性
        const targetAttr = item.attributes.find(attr => attr.trait_type === TARGET_TRAIT_TYPE);
        if (targetAttr && targetAttr.value === TARGET_VALUE) {
          count++;
        }
      });
      console.log(`特征${TARGET_TRAIT_TYPE}为${TARGET_VALUE}的总出现次数:`, count);
    } catch (parseErr) {
      console.log('JSON解析失败:', parseErr);
    }
});
逻辑说明
  • 提前定义要统计的目标trait_type和value,方便后续修改统计规则
  • 读取文件后增加try/catch捕获JSON解析异常,避免程序意外崩溃
  • 遍历所有元数据条目,用find方法匹配对应特征类型
  • 匹配到目标值后计数累加,最终输出统计结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:45:04