简体   繁体   中英

json object properties

I am trying to iterate over this 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"
        }

    }
}

I read this from a file, then parse it and pass it into jade template:

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});
});

then within Jade template I am trying to display the properties nicely:

h1='Config Form'
    p

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

And the outcome is almost there but I am missing the actual names of the object and can't figure how to get it:

Config Form

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

the console.dir(object) will only show it's portion within the {} and no name (such as "welcome_message") but I can't figure how to access it from within the config_form itself.

There is NO way of knowing which object it came from.

Although, you can modify your loops to achieve this. Like this,

- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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