我们是否可以在javascript或js格式的另一个Json文件中导入或导入Json文件
在我的项目中,我有两个Json文件 1) File1.json我们是否可以在javascript或js格式的另一个Json文件中导入或导入Json文件,javascript,json,angularjs,Javascript,Json,Angularjs,在我的项目中,我有两个Json文件 1) File1.json { "abc" : 123 } { "xyz": 567 } 2) File2.json 导入File1.json { "abc" : 123 } { "xyz": 567 } 我需要一个javascript或angular js的方法,这将帮助我实现一个文件 File3.json,其内容如下 { "abc" : 123 }, { "xyz": 567 } 您可以使用节点和文件系统 您需要将文件内容
{
"abc" : 123
}
{
"xyz": 567
}
2) File2.json
导入File1.json
{
"abc" : 123
}
{
"xyz": 567
}
我需要一个javascript或angular js的方法,这将帮助我实现一个文件
File3.json,其内容如下
{
"abc" : 123
},
{
"xyz": 567
}
您可以使用节点和文件系统 您需要将文件内容更改为:
{
"array": [
{
"abc": 123
}
]
}
及
然后你可以这样做:
const fs = require('fs'); // Require Filesystem
let files = ['/File1.json', '/File2.json']; // The files you want to merge
let newData = { 'array': [] }; // The new data object.
files.map( ( file ) => { // Loop the files
fs.readFile( file, function read(err, data) { // Read file and pass data and the response
if (err) { // Handle error
throw err;
}
let parsedJson = JSON.parse(data) // Turn data into JSON
parsedJson.array.map( ( object ) => { // Loop the array of objects.
newData.array.push(object); // Push the object into the new structure.
});
});
})
fs.writeFileSync('/File3.json', newData); // Write the new file.
实际上我没有运行这个,但这个应该可以运行
我还建议您使用数据库,而不是处理JSON文件中的数据。签出Mongo DB它可以为您完成所有这些:)“File3.json,其内容将类似于此”-这是无效的json。它可以类似于此,对吗?[{“abc”:123},{“xyz”:567}]您还可以完全删除.array并生成对象[{“abc”:123}]谢谢Nicolay!但我必须采用这种方法,因为在国际化过程中,我动态加载moduleName-eN.json。但是,有一个常见的-[languageCode].json需要与moduleName-[languageCode].json一起加载。啊,你能不能把文件的内容合并起来并保存为常量?嘿@Nicolay!我刚刚找到了一个方法来实现我想要的。并通过承诺链实现了这一目标。:)