Nodejs读取JSON文件,写入到新文件

const yourArray = [
  {
    meta: { title: "首页" },
    children: [
      {
        meta: { title: "数据" },
        children: [
          {
            meta: { title: "数据A" },
            children: []
          }
        ]
      }
    ]
  },
  {
    meta: { title: "店铺" },
    children: []
  }
];

把这个数据meta.title做为key转成

{
    "首页": {
      "数据": {
      		"数据A":null
      },
    },
    "店铺": nulll
}

方法

const fs = require('fs');

// 读取 JSON 文件
fs.readFile('routes.json', 'utf8', (err, data) => {
  if (err) {
    console.error('读取文件时发生错误:', err);
    return;
  }

  try {
    const jsonData = JSON.parse(data);
    const titles = createJsonFromArray(jsonData);
   console.log(titles)
    // 创建包含标题的新 JSON 对象
    const outputData = { titles };

    // 将数据写入新的 JSON 文件
    fs.writeFile('output-arr.json', JSON.stringify(outputData, null, 2), 'utf8', (writeErr) => {
      if (writeErr) {
        console.error('写入文件时发生错误:', writeErr);
      } else {
        console.log('标题已成功写入 output.json 文件。');
      }
    });
  } catch (parseError) {
    console.error('解析 JSON 时发生错误:', parseError);
  }
});

// 递归函数来提取标题
function createJsonFromArray(arr) {
  const result = {};
  for (const item of arr) {
    const key = item.meta.title;
    if (item.children && item.children.length > 0) {
      result[key] = createJsonFromArray(item.children);
    } else {
      result[key] = null;
    }
  }
  return result;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值