json对象属性

时间:2014-10-10 04:13:05

标签: json node.js express iterator pug

我正在尝试迭代这个JSON:

{
    "info":{
        "version": "0.0.1",
        "status": "prototype"
    },

    "config":{
        "display_random": true,
        "welcome_message": "Welcome to MagSee!",
        "welcome_display_sec": 10
    },

    "config_form":{

        "display_random":{
            "label":"Display Random Image on Start",
            "type": "Boolean",
            "default": true
        },

        "welcome_message":{
            "label": "Welcome Message",
            "type": "TextInput",
            "default": "Welcome to MagSee"
        }

    }
}

我从一个文件中读取它,然后解析它并将其传递给jade模板:

router.get('/view_config', function(req, res){
    var fs = require('fs');
    var file = './config.json';
    var json_data = null;

    var buffer = fs.readFileSync(file, 'utf8');
    json_data = JSON.parse(buffer);

    if (json_data == null){
        console.log('Null json_data. Does the file exist?');
        //todo: need to return 500/null config data message instead
        return;
    }

    res.render('admin_view_config',{'config': json_data.config, 'config_form': json_data.config_form});
});

然后在Jade模板中我试图很好地显示属性:

h1='Config Form'
    p

    ul
        each object in config_form
            li=object
            - console.dir(object)
                ul
                    each value, key in object
                        li=key+": "+value

结果几乎就在那里,但我错过了对象的实际名称,无法弄清楚如何获得它:

配置表格

[object Object]
label: Display Random Image on Start
type: Boolean
default: true
[object Object]
label: Welcome Message
type: TextInput
default: Welcome to MagSee

console.dir(object)只会在{}中显示它的部分而没有名称(例如“welcome_message”),但我无法想象如何从config_form本身访问它。

1 个答案:

答案 0 :(得分:0)

NO方式知道它来自哪个物体。

虽然,您可以修改循环来实现此目的。像这样,

- for(i=0; i<Object.keys(config_form).length; i++)
   - var key = Object.keys(config_form)[i]
        li=key
        - console.dir(config_form[key])
            ul
              each val, index in config_form[key]
                li= index + ': ' + val