📅  最后修改于: 2020-09-23 04:40:10             🧑  作者: Mango
在上一章节中,我们了解了Python中的Datetime转为json数据.
现在我们继续了解Set如何转换未json数据。
JSONEncoder
类,并重写default()
方法,在default()方法中将set
转换为成list
import json
from json import JSONEncoder
# subclass JSONEncoder
class setEncoder(JSONEncoder):
def default(self, obj):
return list(obj)
sampleSet = {25, 45, 65, 85}
print("Encode Set and Printing to check how it will look like")
print(setEncoder().encode(sampleSet))
print("Encode Set nto JSON formatted Data using custom JSONEncoder")
jsonData = json.dumps(sampleSet, indent=4, cls=setEncoder)
print(jsonData)
# Let's load it using the load method to check if we can decode it or not.
setObj = json.loads(jsonData, object_hook=customSetDecoder)
print("Decode JSON formatted Data")
print(setObj)
打印结果如下:
Encode Set and Printing to check how it will look like
[65, 25, 85, 45]
Encode Set nto JSON formatted Data using custom JSONEncoder
[
65,
25,
85,
45
]
Decode JSON formatted Data
[65, 25, 85, 45]
jsonpickle是一个Python库,旨在与复杂的Python对象一起使用。具体的使用方法可以查阅https://www.imangodoc.com/4541.html,我们有介绍安装、使用。
import json
import jsonpickle
from json import JSONEncoder
sampleSet = {25, 45, 65, 85}
print("Encode set into JSON using jsonpickle")
sampleJson = jsonpickle.encode(sampleSet)
print(sampleJson)
# Pass sampleJson to json.dump() if you want to write it in file
print("Decode JSON into set using jsonpickle")
decodedSet = jsonpickle.decode(sampleJson)
print(decodedSet)
# to check if we got set after decoding
decodedSet.add(95)
print(decodedSet)
打印输出如下:
Encode set into JSON using jsonpickle
{"py/set": [65, 25, 85, 45]}
Decode JSON into set using jsonpickle
{65, 45, 85, 25}
{65, 45, 85, 25, 95}
——>>>>>>