This is complete coded up answer that will correctly print any arbitrarily large decimal number. Unfortunately, you must use the DecimalEncoder class to return the value as a string. When I run this code stand alone I get exactly what I want. (remember this is being used for testing and I want to be sure that python isn't changing the value somehow). So when I get the value back from the database I can compare the value correctly without python rounding or clipping the value.
This solution in my testing environment, for some reason, rounds the last digit but no longer clips to 11 digits of precision. Swapping the json.loads calls will show the original issue.
Unfortunately this changes the type of the data to a string and I still have to figure out why my code is rounding the value for the comparison but I can figure that out on the weekend :). Thanks for everybody's help!!
import json
import decimal # use decimal to tell python to leave my numbers alone
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
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( '{ "fldName":4.9497474683058327445566778899001122334455667788990011 }' )
value = str( myJSON.GetJSONChunk ( 'fldName' ))
print str( type( value ))
print value
Output:
<type 'str'>
4.9497474683058327445566778899001122334455667788990011