js 读取本地的json,并遍历执行函数

现本地有一个json文件(E盘),我想读取这个json文件,并对其进行循环执行某个函数
我原本大致这么写:

var alldata=[
    {
        "city": "北京",
        "province": "北京",
        "comment": null,
        "years": null
    },
    {
        "city": "重庆",
        "province": "重庆",
        "comment": null,
        "years": null
    }]

function Function(){
    for(var i in alldata){
        dosomething(alldata[i].city)
    }
} 

dosomething函数里传入city就好。
但我这个json很长,写在这个页面就太长了。所以希望把这个json写在本地,然后读取json再遍历执行。

阅读 1.9k
1 个回答
const fs = require("fs");
// 1,读取文件的路径
// 2,读取文件的编码格式
// 3,当文件读取完成,调用这个callback回调函数来读取文件的结果
fs.readFile("./**.json", "utf-8", function(error, data) {
  if (error) return console.log("读取文件失败,内容是" + error.message);
  console.log("读取文件成功,内容是" + data);
});

需要用node

推荐问题