【问题标题】:How to get attributes from a JSON file to an EJS file?如何从 JSON 文件获取属性到 EJS 文件?
【发布时间】:2020-12-10 08:24:34
【问题描述】:

我有这个 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 文件上?谢谢!

【问题讨论】:

    标签: javascript node.js json api ejs


    【解决方案1】:

    以防其他人想知道。我能够通过将 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
    

    【讨论】:

      【解决方案2】:

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

      const noParsedData = { "car": { "quantity": 2, "price": 100 } }
      
      const parsedData = JSON.parse(noParsedData)
      

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

      注意:它也适用于数组。

      【讨论】:

        猜你喜欢
        • 2016-07-26
        • 1970-01-01
        • 1970-01-01
        • 2020-03-08
        • 2019-04-17
        • 2019-06-02
        • 2011-12-13
        • 1970-01-01
        • 2021-06-16
        相关资源
        最近更新 更多