Having a small issue with the code below with a recursive error:
100s errors printed ending in this:
RuntimeError: maximum recursion depth exceeded while calling a Python object
As you can see below my code is not recursive so something is happening with the DecimalEncoder.
Code
import json
import decimal # tell json to leave my float values alone
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return decimal.Decimal(o)
#return str(o)
return super(DecimalEncoder, self).default(o)
class JSONUtils:
def __init__( self, response ):
self.response = response
self.jsonData = None
self.LoadData( )
print 'jsonData: ' + json.dumps( self.jsonData, cls=DecimalEncoder, indent=2 )
def LoadData ( self ):
if ( self.jsonData == None ):
if ( type( self.response ) == str or type( self.response ) == unicode ):
#self.jsonData = json.loads(self.response )
self.jsonData = json.loads(self.response, parse_float=decimal.Decimal )
def GetJSONChunk( self, path ):
returnValue = ''
curPath = ''
try:
if ( type( path ) == str ):
returnValue = self.jsonData[path]
elif (type( path ) == list):
temp = ''
firstTime = True
for curPath in path:
if firstTime == True:
temp = self.jsonData[curPath]
firstTime = False
else:
temp = temp[curPath]
returnValue = temp
else:
print 'Unknown type in GetJSONChunk: ' + unicode( type( path ))
except KeyError as err:
ti.DBG_OUT( 'JSON chunk doesn\'t have value: ' + unicode( path ))
returnValue = self.kNoNode
except IndexError as err:
ti.DBG_OUT( 'Index does not exist: ' + unicode( curPath ))
returnValue = self.kInvalidIndex
return returnValue
myJSON = JSONUtils( unicode('{ "fldName":4.9497474683058327445566778899001122334455667788990011 }' ))
value = str( myJSON.GetJSONChunk ( 'fldName' ))
print str( type( value ))
print value
If I swap return decimal.Decimal(0) for a string. It gets rid of the error BUT the value as you can see, is returned as a string.
#return decimal.Decimal(o)
return str(o)
This output is close but I need a double at the type:
jsonData: {
"fldName": "4.9497474683058327445566778899001122334455667788990011"
}
<type 'str'>
4.9497474683058327445566778899001122334455667788990011
If I swap these lines you can see the original issue which looses precision.
#self.jsonData = json.loads(self.response )
self.jsonData = json.loads(self.response, parse_float=decimal.Decimal )