简体   繁体   English

通过node.js中导入的json进行交互并进行表达,然后使用玉显示

[英]Interating through imported json in node.js and express, then displaying with jade

After looking at the examples and answers given in related questions here on StackExchange and trying to use them to resolve my issue, I'm finally posting my question. 在查看了StackExchange上相关问题中给出的示例和答案并尝试使用它们来解决我的问题之后,我终于发布了我的问题。 Grrr.... rr ...

So My goal is to eventually access some complex json via api and REST. 所以我的目标是最终通过api和REST访问一些复杂的json。 I was hoping to import (currently via require but eventually via Oauth'd RESTful API) json, parse it to discover the key/value pairs (including nested keys and values) and then at the very least create an object I could then display and have access to all elements. 我希望导入(当前通过require,但最终通过Oauth的RESTful API)json,解析它以发现键/值对(包括嵌套的键和值),然后至少创建一个我可以显示并显示的对象。有权访问所有元素。 I hope that's making sense. 我希望这是有道理的。 Anyway, to begin to build that I thought I'd get some example json and require it. 无论如何,要开始构建,我想我会得到一些示例json并要求它。 Well I initally tried some json from the API that I'm going to use but I'm afraid that it was causing issues (well, my inexperience with node, express and jade is really the cause) so I decided to simplify and grab some very simple json. 好吧,我最初从我将要使用的API中尝试了一些json,但是我担心它会引起问题(嗯,我对node,express和jade的经验不足确实是原因),所以我决定简化并掌握一些非常简单的json。 A colorsArray. colorsArray。 So .. now some code. 所以..现在一些代码。 Here's the console output including the error I get after error I get after attempting to render the web page. 这是控制台输出,其中包括在尝试呈现网页后出现的错误后出现的错误。 Please ignore the pathings because I'm using my php oriented Eclipse IDE to run nodeclipse (which is working awesome btw) 请忽略这些路径,因为我使用的是面向PHP的Eclipse IDE运行nodeclipse(顺便说一句,效果很好)

{ colorsArray: 
   [ { colorName: 'red', hexValue: '#f00' },
     { colorName: 'green', hexValue: '#0f0' },
     { colorName: 'blue', hexValue: '#00f' },
     { colorName: 'cyan', hexValue: '#0ff' },
     { colorName: 'magenta', hexValue: '#f0f' },
     { colorName: 'yellow', hexValue: '#ff0' },
     { colorName: 'black', hexValue: '#000' } ] }
Express server listening on port 3000

After some work (with advise from comments and answers below) I'm now getting the following in my browser 经过一些工作(下面有意见和答案的建议),我现在在浏览器中得到以下内容

**Express**

Welcome to Express

[object Object]

I've update code in the sections below to reflect advice. 我在以下各节中更新了代码以反映建议。

Here's my current app.js 这是我当前的 app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

//Load projects as JSON.
var ob = require('./simple.json');
console.log(ob);

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// set object for templates
app.locals('ob' , ob);

// development only
if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);


http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

and current index.js 当前的 index.js

/*
 * GET home page.
 */


exports.index = function(req, res){
  res.render('index', { title: 'Express' , ob: req.body});
  };

index.jade 玉器

extends layout

block content
  h1= title
  p Welcome to #{title}
  p #{ob}



for(var prop in ob)
 p #{ob.colorName}: #{ob.hexValue}

and finally layout.jade 最后是layout.jade

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

ADD-->Initially forgot to add the json file I'm trying to import 添加->最初忘记添加我尝试导入的json文件

{
    "colorsArray":[{
            "colorName":"red",
            "hexValue":"#f00"
        },
        {
            "colorName":"green",
            "hexValue":"#0f0"
        },
        {
            "colorName":"blue",
            "hexValue":"#00f"
        },
        {
            "colorName":"cyan",
            "hexValue":"#0ff"
        },
        {
            "colorName":"magenta",
            "hexValue":"#f0f"
        },
        {
            "colorName":"yellow",
            "hexValue":"#ff0"
        },
        {
            "colorName":"black",
            "hexValue":"#000"
        }
    ]
}

So there you have it. 所以你有它。 Again, I'd LOVE to be able to get the json, parse it to identify the elements (including nested sub-elements) and have it as an object I can access for logic and display. 同样,我希望能够获取json,将其解析以标识元素(包括嵌套的子元素),并将其作为我可以访问的对象进行逻辑和显示。 But right now, I'd be giddy with being able to just display it in the jade and access the object's elements via a loop. 但是现在,我可以将其显示在翡翠中并通过循环访问对象的元素而感到头晕。

Thanks for taking time to look through this and I know this has been answered here in other examples but I've spent a week trying to employ those solutions with no luck 感谢您抽出宝贵的时间来仔细研究这个问题,我知道在其他示例中已经回答了这个问题,但是我花了一个星期的时间来尝试采用那些解决方案,但是没有运气

When node.js requires a json file it automatically parses it . 当node.js需要一个json文件时,它会自动对其进行解析 You are attempting to parse it a second time here: 您正在尝试在这里第二次解析它:

exports.index = function(req, res){
  var ob = JSON.parse(ob);
  res.render('index', { title: 'Express' , ob: ob});
};

Try omitting JSON.parse and pass the object straight to the render method. 尝试省略JSON.parse并将对象直接传递给render方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM