node.js - 将json数组拆分为节点js中的多个json文件
问题描述
我是节点 JS 的新手,我需要为下面的 json 编写两个文件。
[{
{
sourcePguid: '1',
'urn:reference:000000000000000000000000019318': 'General'
},
{
sourcePguid: '2',
'urn:reference:000000000000000000000000019318123': 'General2'
}
}]
输出除外:
{ sourcePguid: '1',
'urn:reference:000000000000000000000000019318': 'General'
}
This should be as one file and below Json should as another file
{
sourcePguid: '2',
'urn:reference:000000000000000000000000019318123': 'General2'
}
如果有人帮助我在节点 JS 中实现输出,请多多关照。
解决方案
你应该从这个简单的片段开始深入挖掘 Node.js
const fs = require('fs').promises // this is the standard module to work with files
const array = [{
sourcePguid: '1',
'urn:reference:000000000000000000000000019318': 'General'
},
{
sourcePguid: '2',
'urn:reference:000000000000000000000000019318123': 'General2'
}]
// Array has many functions to help you, like .map in this case.
// https://devdocs.io/javascript-array/
const arrayOfPromises = array.map(jsonFileContent => {
// I get each occurrence of `array` as parameter and I return back a Promise to avoid to block the Nodejs event loop:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
return fs.writeFile(`./file-${jsonFileContent.sourcePguid}.json`, JSON.stringify(jsonFileContent, null, 2))
})
// I need to wait for async operation to understand when it is finished
Promise.all(arrayOfPromises)
.then(() => {
console.log('files created')
})
.catch(err => {
console.log('error creating the files', err)
})
console.log('this print first')
推荐阅读
- mysql - MariaDB 多个 IN 子句失败
- django - 在 Google Domains 上购买的自定义域上的 Google App Engine
- php - Apache2无法使用公共IP访问
- puppet - 如何在 Puppet 中将字符串转换为整数
- python - 使用 keras 构建 CNN 模型,用于图像文件夹的不均匀训练和测试数据
- cakephp - 数组控制器 cakephp 上的分页
- excel - 在公式中查找和替换文件名并重新计算公式
- javascript - 在 React 应用程序中渲染外部网页
- python - 使用 functools lru_cache,如何确定函数是否返回了缓存数据?
- typescript - 在 PhpStorm 项目中使用带有 Typescript 的 window.openDatabase