2014-10-10 133 views
0

我想這個JSON遍歷: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" 
     } 

    } 
} 

我從文件中讀取這個,然後分析它,並把它傳遞到翡翠的模板:

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

然後玉模板內我試圖很好地顯示屬性:

h1='Config Form' 
    p 

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

而結果幾乎存在,但我錯過了實際名稱o F中的對象,不能圖如何獲得它:

配置表

[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(對象)將只顯示它的{},沒有名稱中部分(如「WELCOME_MESSAGE 「)但我不知道如何從config_form本身訪問它。

回答

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