Vue.js - Write JSON object to local file

前端 未结 2 2038
暖寄归人
暖寄归人 2020-12-14 10:04

Some while ago I started learning Vue.js and a short while after, I started a bigger project, not keeping in mind, that Javascript has limited options to interact with the l

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 10:35

    This is how I edit JSON files in my Vue projects. In this case, if you run the file, it will create a new data.json file and add Price to each JSON object:

    const fs = require("fs");
    
    let cars = [
      {
        Name: "chevrolet chevelle malibu",
        Miles_per_Gallon: 18,
        Cylinders: 8,
        Displacement: 307,
        Horsepower: 130,
        Weight_in_lbs: 3504,
        Acceleration: 12,
        Year: "1970-01-01",
        Origin: "USA"
      },
      {
        Name: "buick skylark 320",
        Miles_per_Gallon: 15,
        Cylinders: 8,
        Displacement: 350,
        Horsepower: 165,
        Weight_in_lbs: 3693,
        Acceleration: 11.5,
        Year: "1970-01-01",
        Origin: "USA"
      }
    ];
    cars.forEach(car => {
      car.price = 12000;
    });
    
    let data = JSON.stringify(cars);
    fs.writeFileSync("data.json", data);
    

提交回复
热议问题