json - 如何从 JSON 文件获取值并在网站上显示

标签 json node.js express handlebars.js

我正在尝试创建一个 Node.JS 网站。我想从 json 文件中检索数据以正确显示在网站上。我该怎么做呢?我是 Node.JS 新手,不明白在哪里编写脚本。

   {
    "id": "dfd9722a-3ca3-48e7-af2b-633e33d626b5",
    "clientId": "4ef8da99-07ee-4f40-8ea5-be13f4592a62",
    "source": "D346618B-2C9F-4765-940A-B9369BD67114",
    "destination": "",
    "priority": "MEDIUM",
    "reliability": "BEST_EFFORT",
    "eventTime": 1535036080788,
    "eventTimeAsString": "2018-08-23T14:54:40Z",
    "sender": "",
    "type": "DATA",
    "properties": {},
    "direction": "FROM_DEVICE",
    "receivedTime": 1535036083635,
    "receivedTimeAsString": "2018-08-23T14:54:43Z",
    "payload": {
        "format": "urn:oracle:hospitality:lock:attributes",
        "data": {
            "locked": false,
                "Source_FirstName":"John",
                "Source_LastName":"Dunbar"
        }
    }
}

我正在尝试让 John (source_firstname) Dunbar (source_lastname) 出现在我的网站上。我使用 Node.JS、express 和 handbars(作为我的模板引擎)。

<div id="body-container">
<div id="header">
    <div id="logo-content">
        <div id="logo"></div>
    </div>
    <div id="welcome">
        <p>Welcome {{!-- <-- Here goes JSON values }} to Node Park</p>
    </div>
</div> 
{{!-- end of header --}}

这是我的 Node.JS 代码

const express = require('express');
const path = require('path');
const hbs = require('express-handlebars');

// Init App
const app = express();

// Load View Engine
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout', 
layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(__dirname+'/public'));

// Home Route
app.get('/', function(req, res){
  res.render('index', {
    title: 'Node.JS',
    hotel: 'NODEMON'
  });
});

// Start Server
app.listen(5000, function(){
  console.log('Port 5000 open for business.');
});

最佳答案

您可以在服务中请求 json 文件。

//If the json file is in the same root
const json = require("./data.json");

app.get('/', function(req, res){      
  res.render('index', {
    title: 'Node.JS',
    hotel: 'NODEMON',
    firtsName : json.payload.data.Source_FirstName,
    lastName : json.payload.data.Source_LastName
  });
});

并访问html中的firtsNamelastName

<div id="body-container">
<div id="header">
    <div id="logo-content">
        <div id="logo"></div>
    </div>
    <div id="welcome">
        <p>Welcome {{ firtsName }} {{ lastName }} to Node Park</p>
    </div>
</div> 
{{!-- end of header --}}

关于json - 如何从 JSON 文件获取值并在网站上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099310/

相关文章:

jquery ajax外部回调函数

node.js - Haste 模块映射中不存在模块 `fs`

javascript - nodejs createReadStream 从第n行开始

node.js - 如何在 Meteor 1.3 上安装 Cordova 插件

javascript - require 在 node.js 中的行为

python - 解决 python 的 json 模块不喜欢循环引用

c# - 在 C# 中执行多线程事件的奇怪行为

javascript - ExpressJS 需要

node.js - Joi 字段验证基于另一个字段的一组值

json - 使用 Jerkson 解析忽略字段,预计会出现有效值错误