My requirement is to read the json data and to check whether the instance is str/bool/numeric.
My json will look alike jsonObject:
{
"custid": "100001001",
"aNo": 900001001,
"orderId": "xxxxxMN"
}
and my Python code as below:
value_of_keycolumn=jsonObject[columnName]
if isinstance(value_of_keycolumn, str) or isinstance(value_of_keycolumn, bool):
#String or boolean related stuffs
else:
#Numeric related stuffs
It works for string like xxxxxMN
, but when we have number itself as string it was failing. Say for my above json, my expected output is custid and orderId should be str and aNo should be numeric. But my code return custid and aNo as numeric.
Can anyone please help me with it.
CodePudding user response:
you can check that string is number or not with isdigit() function
'122'.isdigit()
True
'ab2'.isdigit()
False
CodePudding user response:
Try creating a composite conditional function that checks if the value is a string, but does not contain only digits.
def isStringButNotNumber(value):
return isinstance(value, str) and not value.isdigit()
def processEntry(key, value):
if isStringButNotNumber(value) or isinstance(value, bool):
# String or boolean related stuff
print("Type of {} is string or boolean ({})".format(key, value))
else:
# Numeric related stuff
print("Type of {} is number ({})".format(key, value))
def processDict(dict):
[processEntry(key, value) for key, value in dict.items()]
if __name__ == '__main__':
processDict({
"custid": "100001001",
"aNo": 900001001,
"orderId": "xxxxxMN"
})
Output
Type of custid is number (100001001)
Type of aNo is number (900001001)
Type of orderId is string or boolean (xxxxxMN)