您的位置:首页 > 编程语言 > Python开发

Python JSON序列化

2014-07-11 15:52 204 查看
Python JSON序列化

import json

# dict to json
d=dict(name="cui",age=20,score=88)
print json.dumps(d)

#list to json
l=["cui",20,88]
print json.dumps(l)

#object to json
class Student(object):
	"""docstring for Student"""
	def __init__(self):
		super(Student, self).__init__()
		self.age=20
		self.name="cui"
		self.score=88

print json.dumps(Student(),default=lambda obj:obj.__dict__)

#json to dict
json_str='{"age": 20, "score": 88, "name": "cui"}'	
d= json.loads(json_str)
print d

#json to list
json_str='["cui", 20, 88]'
l=json.loads(json_str)
print l

#json to object
json_str='{"age": 20, "score": 88, "name": "cui"}'
def dict2Student(d):
	s=Student()
	s.name=d["name"]
	s.age=d["age"]
	s.score=d["score"]
	return s

student=json.loads(json_str,object_hook=dict2Student)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: