gpt4 book ai didi

python - 使用 JSON 保存 Python 元组

转载 作者:IT老高 更新时间:2023-10-28 12:52:52 26 4
gpt4 key购买 nike

我对此还是有点陌生​​,所以我可能不知道所有事物的常规术语:

使用 JSON 编码时是否可以保留 Python 元组?现在 json.loads(json.dumps(tuple)) 给了我一个列表。我不想将我的元组转换为列表,但我想使用 JSON。那么,有什么选择吗?

原因:我正在创建一个使用多维数组的应用程序,并不总是相同的形状。我有一些使用递归来探测数组并将端点转换为字符串或整数的类方法。我最近意识到(基于我的递归工作方式)我可以使用元组来防止对数组进行更深层次的递归搜索(Python rawks)。在我确信我不需要深入探究我的数据结构的情况下,这可能会派上用场。

最佳答案

您可以编写高度特化的编码器和解码器 Hook :

import json

class MultiDimensionalArrayEncoder(json.JSONEncoder):
def encode(self, obj):
def hint_tuples(item):
if isinstance(item, tuple):
return {'__tuple__': True, 'items': item}
if isinstance(item, list):
return [hint_tuples(e) for e in item]
if isinstance(item, dict):
return {key: hint_tuples(value) for key, value in item.items()}
else:
return item

return super(MultiDimensionalArrayEncoder, self).encode(hint_tuples(obj))

def hinted_tuple_hook(obj):
if '__tuple__' in obj:
return tuple(obj['items'])
else:
return obj


enc = MultiDimensionalArrayEncoder()
jsonstring = enc.encode([1, 2, (3, 4), [5, 6, (7, 8)]])

print jsonstring

# [1, 2, {"items": [3, 4], "__tuple__": true}, [5, 6, {"items": [7, 8], "__tuple__": true}]]

print json.loads(jsonstring, object_hook=hinted_tuple_hook)

# [1, 2, (3, 4), [5, 6, (7, 8)]]

关于python - 使用 JSON 保存 Python 元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com