我有一个JSON文件,其中包含两种数组,即Person和Cars。 每个人都有一个身份证,每个人都有一辆车或多辆车。每种汽车也有身份证。 首先,我想创建一个新目录。在该目录中,我想创建名为 (first_name 和 last_name( 的新 JSON 文件。在该文件中,我想选择具有相同ID的人和汽车,并将它们存储在JSON文件中。我不想使用循环。我可以创建目录,但未创建 JSON 文件。
json 文件的外观示例:
JSON 文件:
{
"persons": [{
"id": 1,
"first_name": "Jos",
"last_name": "Vertommen",
"birth_day": "1974-03-23",
"gender": "M",
"married": true,
"image": "https://via.placeholder.com/200x80.png?text=Jos",
"yearsService": 12
}],
"cars": [{
"id": 1,
"license": "1-AAA-123",
"brand": "Opel",
"model": "Zafira",
"personId": 1
}]
节点.js文件
'use strict';
let fs = require("fs");
let jsondata = require("../persons.json");
fs.mkdtemp("cars", (err) => {
if (err) throw err;
fs.readFile('../persons.json', 'utf-8', (err, data) => {
if (err) throw err;
jsondata = JSON.parse(data);
let persons = jsondata.persons;
let cars = jsondata.cars;
if (persons.id === cars.id) {
jsondata = JSON.stringify(data)
let naam = (persons["first_name"] + "_" + persons["last_name"]).toString();
fs.writeFile(`cars/${naam}.json`, jsondata, () => {})
} else {
console.log(err);
}
})
});
我 idk 你的文件系统和你的代码。
我刚刚在 github 上创建了以下示例
在与代码相同的目录中,我添加了一个persons.json
文件,如下所示。
{
"persons": [
{
"id": 1,
"first_name": "Jos",
"last_name": "Vertommen",
"birth_day": "1974-03-23",
"gender": "M",
"married": true,
"image": "https://via.placeholder.com/200x80.png?text=Jos",
"yearsService": 12
},
{
"id": 2,
"first_name": "Halil",
"last_name": "Cakar",
"birth_day": "1992-09-02",
"gender": "M",
"married": false,
"image": "https://via.placeholder.com/200x80.png?text=Halil",
"yearsService": 12
}
],
"cars": [
{
"id": 1,
"license": "1-AAA-123",
"brand": "Opel",
"model": "Zafira",
"personId": 1
},
{
"id": 2,
"license": "1-AAA-123",
"brand": "Opel",
"model": "Zafira",
"personId": 1
},
{
"id": 3,
"license": "1-AAA-123",
"brand": "Opel",
"model": "Zafira",
"personId": 2
}
]
}
"use strict";
let fs = require("fs");
fs.readFile("./persons.json", "utf-8", (err, data) => {
if (err) throw err;
data = JSON.parse(data);
let persons = data.persons;
let cars = data.cars;
// for every person in this persons array
for (let i = 0; i < persons.length; i++) {
// we are getting person
let person = persons[i];
// filtering every car he have!
let personCars = cars.filter((ch) => ch.personId === person.id);
// create file name
let filename = `${person.first_name.toLowerCase()}_${person.last_name.toLowerCase()}.json`;
// i'm just gonna assume that u want to create your files stringified again so
// create person's json data
let data = JSON.stringify({ person, cars: personCars });
// so here we are assuming again that u have a cars/ directory in the same path
fs.writeFile(`./cars/${filename}`, data, () => {
// i'm not sure what to use for this maybe consoling every person's file created!
console.log(person.first_name, " file created!");
});
}
});