当前位置 : 主页 > 编程语言 > python >

Python从门到精通(五):文件处理-03-Json文件处理

来源:互联网 收集:自由互联 发布时间:2022-06-27
需要引入json库 一、json库的使用 import json data = { 'course' : 'python' , 'total_class' : 30 , 'score' : 0.3 } #str2json json_str = json . dumps ( data ) #json2str data = json . loads ( json_str ) # Writing JSON data with open (

需要引入json库

一、json库的使用

import json
data = {
'course' : 'python',
'total_class' : 30,
'score' : 0.3
}
#str2json
json_str = json.dumps(data)
#json2str
data = json.loads(json_str)


# Writing JSON data
with open('data.json', 'w') as f:
json.dump(data, f)

# Reading data back
with open('data.json', 'r') as f:
data = json.load(f)

#类型设置dumps result: {"a": true, "b": "Hello", "c": null}
print(json.dumps(False))
str_dict = {'a': True,
'b': 'Hello',
'c': None
}
print(f'dumps result: {json.dumps(str_dict)}')

二、自定义json返回类型

#一般来说json会返回dict或list,可通过object_hook或object_pairs_hook自定义
s = '{"course": "python", "total_class": 30, "score": 0.3}'
from collections import OrderedDict
data = json.loads(s, object_pairs_hook=OrderedDict)
print(f'data loads: {data}')

#转换为json对象
class JSONObject:
def __init__(self, d):
self.__dict__ = d

data = json.loads(s, object_hook=JSONObject)
print(f'course is: {data.course}')
print(f'total class is: {data.total_class}')
print(f'score is: {data.score}')

三、序列化与反序列化

一般对象实例都不是可以序列化的,需要自定义实现

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

p = Point(1, 3)
# print(f'dumps: {json.dumps(p)}')


def serialize_instance(obj):
d = { '__classname__' : type(obj).__name__ }
d.update(vars(obj))
return d


# Dictionary mapping names to known classes
classes = {
'Point' : Point
}

def unserialize_object(d):
# clsname = d.pop('__classname__', None)
if (clsname := d.pop('__classname__', None)):
cls = classes[clsname]
obj = cls.__new__(cls) # Make instance without calling __init__
for key, value in d.items():
setattr(obj, key, value)
return obj
else:
return d


p = Point(2,3)
s = json.dumps(p, default=serialize_instance)
a = json.loads(s, object_hook=unserialize_object)
print(f'json loads: {a}')
print(f'a x is: {a.x}')
print(f'a y is: {a.y}')
网友评论