1. 程式人生 > >python通過定製路徑的方式解析介面返回資料

python通過定製路徑的方式解析介面返回資料

該問題基於http://stackoverflow.com/questions/7320319/xpath-like-query-for-nested-python-dictionaries的討論,原始碼來自於pyresttest的實現。

問題:在做介面測試時,經常需要檢查返回的json資料中某個欄位是否符合預期。固然可以在程式碼裡寫死要檢查的欄位,但不太靈活,希望能用路徑的方式來訪問欄位。例如如下結構的json資料,定義路徑data.0.name,代表responsedata['data'][0]['name']

{
	data : [
		{
			name : 'bob',
			tel : '12345'
		},
		{
			name : 'alice',
			tel	: '234565'
		}
	],
	total : 1,
	page : 1,
}


程式碼

    def query_dictionary(query, dictionary, delimiter='.'):
        """ Do an xpath-like query with dictionary, using a template if relevant """
        # Based on
        # http://stackoverflow.com/questions/7320319/xpath-like-query-for-nested-python-dictionaries

        try:
            stripped_query = query.strip(delimiter)
            if stripped_query:
                for x in stripped_query.split(delimiter):
                    try:
                        x = int(x)
                        dictionary = dictionary[x]
                    except ValueError:
                        dictionary = dictionary[x]
        except:
            return None
        return dictionary

分析:

query_dictionary使用'.'作為路徑層級之間的間隔,也可以替換成其他符號。這段程式碼可以滿足一般介面測試的要求,

將定義的字串和預期值寫在配置檔案中,無疑會帶來很大的靈活性。如果你期望更強大的路徑定製功能,還可以使

第三方庫jmespath,它的官網是jmespath.org

response = urllib.urlopen('your-get-url')
responsedata = json.loads(response.read())
print query_dictionary('data.0.name', responsedata)
print query_dictionary('data.1.tel', responsedata)
print query_dictionary('total')