首页 > 解决方案 > 将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

解决方案


你应该从这个简单的片段开始深入挖掘 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')

推荐阅读