python實現判斷json是否存在某個key

具體代碼以下:
class checkJSON(object): 
  def getKeys(self,data):
  keysAll_list = []
  def getkeys(data): # 遍歷json全部key
  if (type(data) == type({})):
   keys = data.keys()
   for key in keys:
   value = data.get(key)
   if (type(value) != type({}) and type(value) != type([])):
   keysAll_list.append(key)
   elif (type(value) == type({})):
   keysAll_list.append(key)
   getkeys(value)
   elif (type(value) == type([])):
   keysAll_list.append(key)
   for para in value:
   if (type(para) == type({}) or type(para) == type([])):
   getkeys(para)
   else:
   keysAll_list.append(para)
   getkeys(data)
   return keysAll_list


def isExtend(self,data,tagkey): #檢測目標字段tagkey是否在data(json數據)中
if(type(data)!=type({})):
print('please input a json!')
else:
key_list=self.getKeys(data)
for key in key_list:
if(key==tagkey):
return True
return False

if __name__ == '__main__':
cjson=checkJSON()
data={
"code": 0,
"msg": "ok",
"data": {
"list": [
{
"stock_id0": "601318.SH",
"stock_code0": "601318",
"stock_name0": "中國平安",
},{
"stock_id1": "600000.SH",
"stock_code1": "600000",
"stock_name1": "浦發銀行",
}
]
},
"pass":{
"stock_id2": "600000.SH",
"stock_code2": "600000",
"stock_name2": "浦發銀行",
},
"call_stack": ""
}
list=cjson.getKeys(data)
print(list)
print(cjson.isExtend(data,'stock_name0'))


測試結果以下:

相關文章
相關標籤/搜索