2014-09-24 201 views
1

我想開發一個使用json來描述數據的測試自動化框架。 我有一個JSON文件,該文件是這樣的:我可以在同一個json文件中引用另一個對象中的一個json對象嗎?

{ 
    "preparation":{ 
    "configuration":[ 
     { 
     "config1":{ 
      "src_configfile":"/home/xxx/etc/src_config1.cfg", 
      "dest_configfile":"/home/xxx/etc/abc.cfg" 
     } 
     }, 
     { 
     "config2":{ 
      "src_configfile":"/home/xxx/etc/src_config2.cfg", 
      "dest_configfile":"/home/xxx/etc/xyz.cfg" 
     } 
     } 
    ], 
    "executable_info1":[ 
     { 
     "login_info":{ 
      "hostname":"abc.dw", 
      "username":"xyz", 
      "password":"*******" 
     } 
     }, 
     { 
     "command":{ 
      "folderpath":"/home/xxx/yyy/bin", 
      "processname":"sys.exe", 
      "parameters":"-d" 
     } 
     } 
    ], 
    }, 
    "execution":[ 
    { 
     "test_case1":{ 
     "folderpath":"/home/xxx/testscripts", 
     "scriptname":"test_case1.py", 
     ***???????????Can I access the config1 object here???????????? 
     "config_file"="preparation.configuration[0].config1.dest_configfile"*** 
     } 
    }, 
    { 
     "test_case1":{ 
     "folderpath":"/home/xxx/testscripts", 
     "scriptname":"test_case2.py", 
     ***"config_file"="preparation.configuration[1].config2.dest_configfile"*** 
     } 
    } 
    ] 
} 

我需要使用不同的配置文件用於不同的測試用例。我可以在執行中引用準備對象的config1對象嗎?

+1

據我所知,不是純粹的JSON。現在,您可以在解析時創建一些標記,並在創建對象時引用該對象。所以'obj = JSON.parse(json)',然後循環訪問'obj'的屬性'值並引用其他屬性,如果它匹配某種語法(即'preperation.configuration [0] .config1.dest_configfile')。 – Sam 2014-09-24 18:11:14

+0

爲什麼你需要在那裏引用config1對象?我假設無論運行時應用程序使用這個,只需要知道要使用哪個配置(即只是config1屬性名稱),而不需要引用整個對象路徑。 – 2014-09-24 18:43:26

回答

1

不,你不能那樣做,至少不是直接。首先,JSON不支持循環引用。

你可能會考慮使用一個庫,比如jsonpath,它允許你通過模式來引用元素,但是你往往需要先驗值是一個實際值還是對某個其他分支的引用。