簡體   English   中英

如何從 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)

當您這樣做時,生成的日期應該是 object。 現在您可以在文件中使用該 object 的鍵和值。

注意:它也適用於 arrays。

以防其他人疑惑。 我可以通過將 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM