使用node.js将多个对象读写到json文件

时间:2014-09-06 15:24:35

标签: javascript json node.js

我有一个正在读取我的json文件的函数,然后它应该在那里写入(更新)一个字段并更改原始文件,如果密钥存在于json文件中,则完成此操作。 问题是我一次插入多个对象,如果对象不在json文件中,我的函数没有做任何事情(不更新文件)。 这是我的Json文件:

{
    "NVDA": {
        "name": "Nvidia Corporation",
        "symbol": "NVDA",
        "logo": "nvidia.png",
        "price": 0,
        "prod": "Nvidia Corporation, gforce, g-force, shield"
    },
    "AAPL": {
        "name": "Apple inc",
        "symbol": "AAPL",
        "logo": "apple.png",
        "price": 2,
        "prod": "Apple inc, mac, macbook, iphone, ipod, ipad, osx"
    },
    "GOOG": {
        "name": "Google inc",
        "symbol": "GOOG",
        "logo": "google.png",
        "price": 0,
        "prod": "search, android, glass, drive, code school"
    },
    "IBM": {
        "name": "ibm",
        "symbol": "ibm",
        "logo": "google.png",
        "price": 1,
        "prod": "search, android, glass, drive, code school"
    }
}

这是我的功能:

function updateJson(data, callback) {
    var ticker = data.ticker;
    var value = data.value;
    //var stocksJson = JSON.parse(fs.readFileSync("stocktest.json"));
    fs.readFile('stocktest.json', function(error, file) {
        if (error) {
            console.error(error);
            callback(error);
        }
        var stocksJson =  JSON.parse(file);

        if (stocksJson[ticker]!=null) {
            console.log(ticker+" price : " + stocksJson[ticker].price);
            console.log("changing the value...")
            stocksJson[ticker].price =  value;
            console.log("Price after the change has been made -- " + stocksJson[ticker].price);
            console.log("printing the the Json.stringify")
            console.log(JSON.stringify(stocksJson, null, 4));
             fs.writeFile('stocktest.json',JSON.stringify(stocksJson, null, 4) , function(err) {  
                            if(!err) {
                                callback(null, "File successfully written");
                            }
                            if (err) {
                                console.error(err);
                                callback(err);
                            }

                       }); // end of writeFile
        }
        else {
            console.log(ticker + " not in the json");
            callback(ticker + " doesn't exist on the json");
        }
    }); // end of readFile
} // end of updaJson

var arr = [];
arr.push({ticker:"IB", value:1});
arr.push({ticker:"AAPL", value:2});
 console.log("printinhg the array.....")
for(var i=0; i<arr.length; i++) {
    console.log(arr[i]);
}

async.eachSeries(arr, updateJson, function(err, success) {
  console.log('All items have been updated');
});

0 个答案:

没有答案
相关问题