首页 > 解决方案 > 将json数组直接反序列化为python中的集合

问题描述

有没有办法将 json 数组直接反序列化为一个集合?

data.json(是的,这只是一个 json 数组。)

["a","b","c"]

请注意,json 数组包含唯一元素。

目前我的工作流程如下。

open_file = open(path, 'r') 
json_load = json.load(open_file) # this returns a list
return set(json_load) # which I am then converting to a set. 

有没有办法做这样的事情?

open_file = open(path, 'r') 
return json.load(open_file, **arguments) # this returns a set.

还有没有其他方法可以在没有 json 模块的情况下做到这一点?当然,我不是第一个需要一套解码器的人。

标签: pythonpython-3.x

解决方案


不,您必须继承其中一个 json 模块类JSONDecoder并覆盖创建对象的方法,才能自己完成。

而且这也不值得麻烦。json 数组真正映射到 python 中的列表——它们有顺序,并且可以允许重复——一个集合不能正确地表示一个 json 数组。因此,提供一个集合不是 json 解码器的工作。

转换是你能做的最好的。您可以创建一个函数并在需要时调用它:

def json_load_set(f):
    return set(json.load(f))

推荐阅读