【Python】python中json、class、str的相互转换参考:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : garbage_test.py
@Time : 2019/06/15 08:26:17
@Author : California Fruit
@Desc : None
'''
import json
class Student(object):
def __init__(self, name, age, score,reward):
self.name = name
self.age = age
self.score = score
def json_2str():
python json字符串转数组data_json = {'name':'nick',
'age':12}
json_str = json.dumps(data_json)
print type(json_str), json_str
def str_2json():
json_str = '{"age": 12, "name": "nick"}'
json_class = json.loads(json_str)
print type(json_class), json_class
def class_2jsonStr():
stu = Student('Bob', 20, 88,["三好学⽣","优秀团⼲","最佳辩⼿"])
print json.dumps(obj=stu.__dict__,ensure_ascii=False)
def jsonStr_2class():
def dict2student(d):
return Student(d['name'], d['age'], d['score'],d['reward'])
json_str = '{"name": "Bob", "age": 20, "score": 88, "reward": ["三好学⽣", "优秀团⼲", "最佳辩⼿"]}'
student = json.loads(json_str,object_hook=dict2student)
print(type(student))
print(student.name)
if __name__ == "__main__":
jsonStr_2class()
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论