Python对象和JSON

2024-04-20 12:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python对象,我将其转储到json并写入一个文件。你知道吗

results = [
{'destination': (x,y), 'id': 'dsss', 'origin': (x,r), 'waypoints': [[s,l],[d,s]]},
{'destination': (x1, y1), 'id': 'ddsdsee', 'origin': (z,f), 'waypoints': [[e,y],[d,e]]}]

with gzip.open("test.json.gz",'w') as outfile:
    json.dump(results,outfile,indent=2)

然后我在其他地方打开文件,通过:

schedule_f = gzip.open("test.json.gz")
schedule = json.load(schedule_f)

pprint(schedule[0])返回:

{'destination': [x,y], 'id': 'dsss', 'origin': [x,r], 'waypoints': [[s,l],[d,s]]

为什么origindestination字段转换为列表?我明确指定了(而不是[


Tags: 文件对象testidjsonoriginopendestination
3条回答

JSON不支持元组,因此json模块将它们转换为JSON支持的数组。你知道吗

嵌套的Python对象可以比允许以JSON格式存储的对象更复杂。当您将JSON格式导入Python时,它只有一个容器及其解析为列表。你知道吗

这种格式转换不是保守的,它们会破坏信息。您将无法存储datetime,它将被转换为字符串。你知道吗

JSON没有任何元组的概念:只有数组,它映射到Python列表。你知道吗

从实用的角度看没有区别,但是如果你认为你真的需要元组,你必须自己转换它们

相关问题 更多 >