获取复杂嵌套list,json对应的下标(key)的value值, 可以取到任意值方法。 类似于Jmeter的JSON Extractor后置处理器
# 获取复杂嵌套list,json对应的下标(key)值
# 格式:keytag: "2.a" dict_data:[{"a": "111", "b": 222}, "bbbb", {"a": "555", "b": 222}]
def get_nestdict_value(self, keytag, dict_data):
if type(dict_data) not in [types.ListType, types.DictType]: # 处理返回值为 "{}" ,"[]"情况
# dict_data = json.loads(dict_data)
dict_data = Core.eval_str(dict_data) # 效果同上
# 处理 "a": "[]" 情况
dict_data = self.dict_handle(dict_data)
sname = keytag.strip()
obj = scmd = realval = ""
for i in sname.split("."):
if Core.is_numeric(i):
obj = "%s[%s]" % (obj, i)
else:
if 'str(' in i:
i = i[i.find('(')+1:-1] # 若有key为数字的,需要做str处理,编写格式为:{"data": {"1001": "A"}} --> data.str(1001)
obj = "%s['%s']" % (obj, i)
scmd = "%s%s" % ("dict_data", obj)
try:
realval = eval(scmd)
except:
return "[Failed]:cmd change error,eval(%s)" % scmd
return realval
# eg
dict_data01 = [{"a": "111", "b": 222}, "bbbb", {"a": "555", "b": 222}]
print get_nestdict_value("1.a", dict_data01)
# 输出
555
dict_data02 = {"kkk": [{"a": "111", "b": 222}, "bbbb", {"a": "555", "b": 222}], "yyy": "Piii"}
print get_nestdict_value("kkk.0.b", dict_data02)
# 输出
222
网友评论