现在移动互联网飞速发展,在测试过程中通常需要进行HTTP接口测试,而大多数http请求返回的是json数据。
然而python对josn数据的解析,就是对字典的解析,以下面这段json为例:
{
"ver": "6.8",
"dcid": "477",
"head": {
"cid": "",
"ctok": "",
"cver": "1.0",
"lang": "01",
"sid": "1",
"syscode": "09",
"auth": "",
"extension": []
},
"contentType": "json"
}
如果我们要获取sid中的数据,需要这样解析
第一种:jsonstr['head']['sid']
第二种:jsonstr.get('head').get('sid')
写完后发现这种方法是不是太low,而且当json层级太深时,代码可视性极差,而且难于维护。
json属于结构化数据,就像html一样,于是考虑到用xpath方法去解析。下面直接上代码:
import json import xmltodict # 解析json字符串 class jsonprase(object): def __init__(self, json_value): try: eval(json_value) self.json_value = json.loads(json_value) except Exception, e : raise ValueError('must be a json str value') def find_json_node_by_xpath(self, xpath): elem = self.json_value nodes = xpath.strip("/").split("/") for x in range(len(nodes)): try: elem = elem.get(nodes[x]) except AttributeError: elem = [y.get(nodes[x]) for y in elem] return elem def datalength(self, xpath="/"): return len(self.find_json_node_by_xpath(xpath)) @property def json_to_xml(self): try: root = {"root": self.json_value} xml = xmltodict.unparse(root, pretty=True) except ArithmeticError, e: pyapilog().error(e) return xml
然后测试一把
a ='''{ "ver": "6.8", "dcid": "477", "head": { "cid": "", "ctok": "", "cver": "1.0", "lang": "01", "sid": "1", "syscode": "09", "auth": "", "extension": [] }, "contentType": "json" }''' print type(a) d = jsonprase(a).find_json_node_by_xpath('/head/sid') print d