Convert python decimal to string in deeply nested and unpredictable list

后端 未结 2 532
悲&欢浪女
悲&欢浪女 2020-12-06 22:52

I am trying to loop through every value in a deeply nested/mixed list and convert any Decimal instances to string so that I can store them in mongo.

My attempt at re

2条回答
  •  抹茶落季
    2020-12-06 23:25

    You want to convert decimals to strings, but recursively apply your function to the contents of lists and the values of dictionaries, otherwise return objects unchanged? Then do that:

    def strip_decimals(o):
        if type(o) == Decimal:
            return str(o)
        elif type(o) == list:
            return map(strip_decimals, o)
        elif type(o) == dict:
            return dict([(k, strip_decimals(v)) for k, v in o.iteritems()])
        else:
            return o
    

    Results in:

    [{'Payments': {'APR': '2.54',
               'AppliedIds': [],
               'CapCostTotal': '27900',
               'IsCapped': True,
               'Name': 'TestData',
               'OtherFees': '0',
               'Payment': '495.64',
               'Program': {'Description': None, 'ProgramName': u'AST'},
               'Rate': '0.0254',
               'Tax': '0'}}]
    

提交回复
热议问题