gpt4 book ai didi

json - 在 NodeJs 中读取 JSON 文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:16 25 4
gpt4 key购买 nike

我有一个包含此内容的小 JSON 文件

{
"users": [
{
"id": 1593,
"name": "Foo Bar"
}
]
}

我想通过使用文件系统模块来读取此内容。所以我的应用程序看起来像这样

const fs = require('fs');
const express = require('express');

const app = express();

app.get('/users/:id', function (req, res) {
fs.readFile('./userDb.json', 'utf8', function (err, data) {
var json = JSON.parse(data);
var users = json.users;

console.log(users[0].id); // returns 1593

console.log(req.params.id); // returns 1593

var userObj = null;

for(var i = 0; i < users.length; i++){
var currentUser = users[i];

console.log(currentUser.id); // returns 1593

if (currentUser.id === req.params.id) { // this should be fine 1593 === 1593
userObj = currentUser;
break;
}
}

console.log(userObj); // returns undefined

res.render('users', {
user: userObj
});
});
});

app.listen(3000, function () {
console.log('Server running on port 3000');
});

当我将其作为参数传递时,日志将始终返回 1593,但当我想要渲染 Handlebars 模板时,分配的对象为 null。

userObj 为 null,即使尝试此代码时也是如此

var userObj = users.find(u => u.id === req.params.id);

但我认为数据库没有错误。我哪里搞错了=?

最佳答案

非常确定req.params.id是一个String。尝试:

const userObj = users.find(u => u.id === Number(req.params.id));
<小时/>

当您对此有疑问时:

console.log(
`First value : ${v1} - ${typeof v1}`,
`Second value : ${v2} - ${typeof v2}`,
);

关于json - 在 NodeJs 中读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47459439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com