python小功能-递归解析Json
2018-04-26 本文已影响21人
灼灼2015
递归.png目的:解析Json格式的接口参数
用途:用于接口自动化测试,避免手工录入接口参数
1
Json格式的接口参数会有多种形式:数组、对象、数组和对象组合模式。
数组的实现方式:
[
{"id" : 1 ,"name" : "zhangsan"},
{"id" : 2 , "name" : "lisi"}
]
对象的实现方式:
{
"meta":{
"name":"南方有乔木",
"cpCode":"mgtv",
"genre":"happy"
}
}
2
将json的参数解析出来并存入参数对象列表中。
def parseParamJson(suite_id):
suite = TestSuite.objects.get(id=suite_id)
paramList = json.loads(suite.json)
newparams = []
parentNodeName = ''
parentNodeType = ''
param = None
typeName = None
parseParam(paramList,parentNodeName,parentNodeType,typeName,param,newparams)
for param in newparams:
print("Param name :" + param.name)
print("Param type :" + str(param.type))
print("Param parentNodeName :" + param.parentNodeName)
print("Param parentNodeType :" + param.parentNodeType)
print("-------------------------------")
def parseParam(paramList,parentNodeName,parentNodeType,typeName,paramName,newparams):
if not paramName is None :
if type(paramName) != dict:
parentNodeName = parentNodeName + '#' + paramName
else:
parentNodeName = parentNodeName + '#' + 'DefaultNodeTest'
if not typeName is None:
parentNodeType = parentNodeType + '#' + typeName
if type(paramList) == list:
for paramName in paramList:
typeName = 'list'
parseParam(paramName, parentNodeName, parentNodeType, typeName,paramName,newparams)
break
elif type(paramList) == dict:
for paramName in paramList:
typeName = 'dict'
paramValue = paramList[paramName]
parseParam(paramValue, parentNodeName, parentNodeType,typeName, paramName,newparams)
else:
param = TestSuiteParam()
param.name = paramName
param.type = type(paramList)
param.parentNodeName = parentNodeName
param.parentNodeType = parentNodeType
newparams.append(param)
3
验证数组
Param name :id
Param type :<class 'int'>
Param parentNodeName :#DefaultNodeTest#id
Param parentNodeType :#list#dict
-------------------------------
Param name :name
Param type :<class 'str'>
Param parentNodeName :#DefaultNodeTest#name
Param parentNodeType :#list#dict
-------------------------------
验证对象
Param name :name
Param type :<class 'str'>
Param parentNodeName :#meta#name
Param parentNodeType :#dict#dict
-------------------------------
Param name :cpCode
Param type :<class 'str'>
Param parentNodeName :#meta#cpCode
Param parentNodeType :#dict#dict
-------------------------------
Param name :genre
Param type :<class 'str'>
Param parentNodeName :#meta#genre
Param parentNodeType :#dict#dict
-------------------------------