【发布时间】:2020-06-29 02:28:58
【问题描述】:
所以我想要实现的是将包含对象的数组加载到 json 中,以便我可以将其解析回程序并在程序中的任何位置使用它。我已经尝试过使用 fs 的方式来执行此操作,但我很快发现当我阅读它时,我无法使用异步回调函数之外的变量。我在问是否有更好的方法将我的充满对象的数组加载到 json 中,读取它并能够在我的程序中的任何地方使用这些变量。我也想要一些见解,因为我想了解更多关于我是新手的主题,谢谢!
我的问题是我无法从异步回调函数访问变量,因为当我从函数本身调用它时它返回 undefined。
class Blockchain {
constructor() {
this.chain = [Blockchain.getGenesis()];
console.log(Blockchain.getGenesis());
}
//further into the code with the issued function reading the data from .json to //place the objects into variables for the program to use
static getGenesis(genChain) {
fs.readFile(jsonRoute, 'utf-8', function(err, data) {
if (err) throw err;
jsonChain = JSON.parse(data);
genesis = jsonChain.blocks[0].GENESIS_DATA;
//console.log(genesis);
/*console.log(jsonChain.blocks[0].GENESIS_DATA.lastHash); //specify element of where the object is and the field that you want to read*/
/*jsonChain.blocks.push({
GENESIS_DATA
});
console.log(jsonChain);
fs.writeFile('CDSM/CDSM.json', JSON.stringify(jsonChain), 'utf-8', function(err) {
if (err) throw err;
console.log('Done!');*/
});
return genesis; //returns undefined since the variable I need to access gets //destroyed before I call it in the constructor (this is a multi module project //and need the array to "save" basically
}
}
.json 文件:
{"blocks":[{"GENESIS_DATA":{"timestamp":1,"lastHash":"v01d","hash":"?M=(((Position-1)=>ter)=>sen)=>non?","difficulty":20,"nonce":0,"data":[]}}]}
由于这种架构限制,我想问是否有不同的方式来读取 json 文件并将其内容引用到变量中。
【问题讨论】:
-
您是在说加载
.json文件吗?原始数据来自哪里?请显示您尝试过的一些代码。 -
将数据加载到采用数组的现有 .json 中。如果我向您展示我的旧代码,请不要尝试构建它,因为我要求不同的架构或不同的执行方式,因为我无法使用 fs 库访问回调异步函数中的变量。
-
抱歉,我认为您对某些术语有些困惑,因此我很难理解您的意思。不过,我会尽力帮助你。你是说你只有一个对象数组,你想在代码的多个地方使用它们?
-
我确信我混淆了术语,但我已经编辑了帖子,现在应该更有意义了
-
啊,我明白了,这很有帮助。我会给你写一个解决方案。
标签: javascript node.js json database parsing