简体   繁体   English

如何使用 node.js 从 json 文件中读取数据

[英]How to read data from a json file using node.js

I need to read my user Id to know what the timestart number is but I don't find the way to read the data.我需要读取我的用户 ID 才能知道 timestart 编号是什么,但我找不到读取数据的方法。

//My code
const fs = require('fs');
var timePath = 'test.json'
var TimeRead = fs.readFileSync(timePath);
var timeFile = JSON.parse(TimeRead); //ready for use
var userId = "2"

var Time = TimeRead.userId.TimeStart; 

console.log(Time)

1 is my user Id variable 1 是我的用户 ID 变量

//My json File
{
  "1": {
    "TimeStart": 1626909816680
  },
  "2": {
    "TimeStart": 1627166305644
  }
}

var Time = TimeRead.userId.TimeStart; 

You can't use a variable with .您不能将变量与.

Try this:试试这个:

var Time = TimeRead[userId].TimeStart; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM