简体   繁体   中英

Best practice to convert 64 bit integers into string in an object for json encoding?

There is a python object which contains some numbers, few of which may be 64 bit integers.

my_page_obj = {'id': 7810094555612199019 ,
                'page':944,
                'blog_data':{'edited':True,
                             'edit_ids':[7810094555612199019,
                                         8810094555612199019 ,
                                         3407830461687591912 ] ,
                 'user':{ 'name':'Van Dam',
                          'split_angle':180 ,
                          'age':44 ,
                          'follows':[5082331655205093463,
                                     492349326714935674,
                                     7116718677923950629]
                  } }

To convert the 64 bit ids to strings is not feasible easily as this data is coming from various data sources, and plays well when used within python scripts. However, when sent as json to Javascript frontent, it gets rounded off due to limitations of 64 bit Javascript Float. It would be preferable to convert only the 64 bit integers into strings and leave the other numbers as is. Their role is known ie the smaller numbers serve some result/data/statistics/count, and all the 64 bit integers are id of something.

What is the best way to deal with this problem ?

  1. Recursively iterate the dictionary, and check instance to be 64 bit integer, and convert ?

  2. Convert to json string, use regex to convert all numbers bigger than some threshold length to strings ? say, numbers more than 9 characters long.

What are the gotchas of both methods ?

I would go for the first option:

def i64str(obj):
    if isinstance(obj, list):
        return [i64str(x) for x in obj]
    if isinstance(obj, dict):
        return {k:i64str(v) for k, v in obj.items()}
    if isinstance(obj, (int, long)) and obj >= 2**32:
        return str(obj)
    return obj

json.dumps(i64str(my_page_obj))

Manipulating structured responses with regexes, especially with numeric comparisons involved is a big no-no in my book.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM