如何从 JSON 文件获取属性到 EJS 文件?

How to get attributes from a JSON file to an EJS file?

我有这个 JSON 文件用作数据库,名为 data.json。

{
 "car": {
 "quantity": 2,
 "price": 100
}

我在 node.js 上有这个名为 app.js

的代码
var data = fs.readFileSync("data.json");
var jData = JSON.parse(data);
// console.log(jData);
 
 
////////ROUTES///////////
app.get("/", home);

// New item create path
app.get("/new/:id/:quantity/:price?", newItem);

function newItem(req, res){
 var itemData = req.params;
 ////// shows :id as name
 var newName = itemData.id;
 ////// shows :price as price
 var newPrice = Number(itemData.price);
 var newQuantity = Number(itemData.quantity);
 var reply;
 //// Object created
 function ItemObj(quantity, price) {
  this.quantity = quantity;
  this.price = price;
 }
 ///// Assing attributes to object
 var createItem =  new ItemObj(newQuantity, newPrice);
 // print stuff
 res.send("This new " + newName + " has been added! and it costs " + 
 newPrice);
 ////// If prices is not set
 if(!newPrice){
 reply = ("price is required")
 //////////then---->
 } else {
  jData[newName] = createItem;
  var stringData = JSON.stringify(jData, null, 2);
  fs.writeFile("data.json", stringData, finished);
  function finished(err, info){
  console.log("updated");
  }
res.render("index", {jData: jData})
}

然后我有一个名为 index.ejs 的 EJS 代码,当我试图将 JSON 数据库 (jData) 传递给 EJS 以显示它们的值时,我收到一条错误消息:“jData 不是定义

 <h1>Hello bro</h1>

 <%= JSON.stringify(jData) %>

我哪里出错了,如何让 json 文件显示在 index.ejs 文件上?谢谢!

将JSON文件导入到你需要数据的文件中,然后你要解析它:

const noParsedData = { "car": { "quantity": 2, "price": 100 } }

const parsedData = JSON.parse(noParsedData)

当你这样做时,结果日期应该是一个对象。现在您可以在文件中使用该对象的键和值。

注意:它也适用于数组。

以防其他人疑惑。我能够通过将 jData 数据库设置为 node.js (app.js):

中的变量来修复错误
var db = jData;
res.render("index", {exampleVar: db});

然后,我不得不在 EJS 文件 (index.ejs) 上使用 stringify() 来修改 JSON 文件:

<h1> Price of item: <%= 
JSON.stringify(exampleVar["car"]["price"]) %> </h1>

在客户端页面上得到结果:

Price of item: 100