【问题标题】:How to push json data from a json file into an array with a new set and update the file如何将 json 文件中的 json 数据推送到具有新集的数组中并更新文件
【发布时间】:2021-10-11 21:07:27
【问题描述】:

我正在使用节点 js 并尝试将一组 JSON 数据保存到文件中。

const products = [];
    fs.readFile(pathToTheFile, (err, data) => { // get the data from the file
        if(data != ''){
            products.push(JSON.parse(data)); // the data is in string format. convert it into JSON and push into the empty arry of products
        }
        products.push(this); // push the form data in to products array after the file data
        fs.writeFile(pathToTheFile, JSON.stringify(products), (err) => { // convert the products array back into string and update the file entirely with the data
            console.log(err);
        });            
    });

但是 JSON 数据是以嵌套方式保存在文件中的。

[
[
    [
        {
            "title": "1",
            "imageUrl": "https://images.pexels.com/photos/279906/pexels-photo-279906.jpeg?cs=srgb&dl=pexels-pixabay-279906.jpg&fm=jpg",
            "description": "wer",
            "price": "1234"
        }
    ],
    {
        "title": "2",
        "imageUrl": "https://images.pexels.com/photos/279906/pexels-photo-279906.jpeg?cs=srgb&dl=pexels-pixabay-279906.jpg&fm=jpg",
        "description": "er3t",
        "price": "21345"
    }
],
{
    "title": "3",
    "imageUrl": "https://images.pexels.com/photos/279906/pexels-photo-279906.jpeg?cs=srgb&dl=pexels-pixabay-279906.jpg&fm=jpg",
    "description": "wew",
    "price": "2345"
}

]

在这种情况下我该怎么办?

编辑:

这是来自我的班级建设者

    constructor(title, imageUrl, description, price) {
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.price = price;
}

我尝试过这样的 concat

 const products = [];
    fs.readFile(pathToTheFile, (err, data) => { // get the data from the file
        if (data != '') {
            products.push(JSON.parse(data)); // the data is in string format. convert it into JSON and push into the empty arry of products
            //console.log(this);
            products.concat(this);
        } else {
            products.push(this); // push the form data in to products array after the file data
        }
        console.log(products);
        fs.writeFile(pathToTheFile, JSON.stringify(products), (err) => { // convert the products array back into string and update the file entirely with the data
            console.log(err);
        });
    });

但是得到一个空数组

[
[
    {
        "title": "",
        "imageUrl": "",
        "description": "",
        "price": ""
    }
]

]

【问题讨论】:

  • datathis 变量的值是多少?在将products 变量写入文件之前,它的值是多少?尝试添加一些 console.logs。

标签: node.js arrays json


【解决方案1】:

您应该使用concat() 方法而不是push()

push() : push() 方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。 (MDN)

var arr1 = [‘a’, ‘b’, ‘c’];
var arr2 = [‘d’, ‘e’, ‘f’];
var arr3 = arr1.push(arr2);
控制台.log(arr3); // 4
控制台.log(arr1); // [“a”,> “b”, “c”, [“d”, “e”, “f”]]

concat() : concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。

var arr1 = [‘a’, ‘b’, ‘c’];
var arr2 = [‘d’, ‘e’, ‘f’];
var arr3 => arr1.concat(arr2);
控制台.log(arr3); //[“a”, “b”, “c”, “d”, “e”, “f”]

【讨论】:

  • 尝试过 concat。我尝试使用 concat 编辑了问题
【解决方案2】:

您正在将一个数组插入到产品数组中。
请参阅下面的正确代码 -

const products = [];
    fs.readFile(pathToTheFile, (err, data) => { // get the data from the file
        if(data != ''){
            products = JSON.parse(data));
        }
        products.push(this);
        fs.writeFile(pathToTheFile, JSON.stringify(products), (err) => {
            console.log(err);
        });            
    });

【讨论】:

  • 这个有效。谢谢。但是我不得不改变 const product = [] 来让 product =[]。你能解释一下这条线吗?产品 = JSON.parse(data));
  • 您需要products 作为全局变量吗?否则,您可以在箭头函数中使用将产品声明为 const。
  • 没关系。知道了。我正在插入数据。我必须把它储存起来。
猜你喜欢
  • 2021-02-06
  • 2016-01-12
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多