对python中Json与object转化的方法详解

yipeiwu_com6年前Python基础

python提供了json包来进行json处理,json与python中数据类型对应关系如下:

python Json与object转化

一个python object无法直接与json转化,只能先将对象转化成dictionary,再转化成json;对json,也只能先转换成dictionary,再转化成object,通过实践,源码如下:

import json

class user:
  def __init__(self, name, pwd):
    self.name = name
    self.pwd = pwd

  def __str__(self):
    return 'user(' + self.name + ',' + self.pwd + ')'

#重写JSONEncoder的default方法,object转换成dict
class userEncoder(json.JSONEncoder):
  def default(self, o):
    if isinstance(o, user):
      return {
        'name': o.name,
        'pwd': o.pwd
      }
    return json.JSONEncoder.default(o)

#重写JSONDecoder的decode方法,dict转换成object
class userDecode(json.JSONDecoder):
  def decode(self, s):
    dic = super().decode(s)
    return user(dic['name'], dic['pwd'])

#重写JSONDecoder的__init__方法,dict转换成object
class userDecode2(json.JSONDecoder):
  def __init__(self):
    json.JSONDecoder.__init__(self, object_hook=dic2objhook)


# 对象转换成dict
def obj2dict(obj):

  if (isinstance(obj, user)):
    return {
      'name': obj.name,
      'pwd': obj.pwd
    }
  else:
    return obj

# dict转换为对象
def dic2objhook(dic):

  if isinstance(dic, dict):
    return user(dic['name'], dic['pwd'])
  return dic

# 第一种方式,直接把对象先转换成dict
u = user('smith', '123456')
uobj = json.dumps(obj2dict(u))
print('uobj: ', uobj)


#第二种方式,利用json.dumps的关键字参数default
u = user('smith', '123456')
uobj2 = json.dumps(u, default=obj2dict)
print('uobj2: ', uobj)

#第三种方式,定义json的encode和decode子类,使用json.dumps的cls默认参数
user_encode_str = json.dumps(u, cls=userEncoder)
print('user2json: ', user_encode_str)

#json转换为object
u2 = json.loads(user_encode_str, cls=userDecode)
print('json2user: ', u2)

#另一种json转换成object的方式
u3 = json.loads(user_encode_str, cls=userDecode2)
print('json2user2: ', u3)

输出结果如下:

C:\python\python.exe C:/Users/Administrator/PycharmProjects/pytest/com/guo/myjson.py
uobj: {"name": "smith", "pwd": "123456"}
uobj2: {"name": "smith", "pwd": "123456"}
user2json: {"name": "smith", "pwd": "123456"}
json2user: user(smith,123456)
json2user2: user(smith,123456)

Process finished with exit code 0

以上这篇对python中Json与object转化的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python语言描述随机梯度下降法

Python语言描述随机梯度下降法

1.梯度下降 1)什么是梯度下降? 因为梯度下降是一种思想,没有严格的定义,所以用一个比喻来解释什么是梯度下降。 简单来说,梯度下降就是从山顶找一条最短的路走到山脚最低的地方。但是因为...

在Python中使用第三方模块的教程

在Python中,安装第三方模块,是通过setuptools这个工具完成的。Python有两个封装了setuptools的包管理工具:easy_install和pip。目前官方推荐使用p...

在python shell中运行python文件的实现

在python shell中运行python文件的实现

最近在学习flask开发,写好程序后需要在python shell中运行测试功能。专门抽时间研究了下,总结以防止以后遗忘。 这是测试文件的结构,python_example主文件夹,下面...

详解python3安装pillow后报错没有pillow模块以及没有PIL模块问题解决

详解python3安装pillow后报错没有pillow模块以及没有PIL模块问题解决

也许自己真的就是有手残的毛病,你说好端端的环境配置好了,自己还在那里瞎鼓捣,我最不想看到的就是在安装一个别的模块的时候,自动卸载了本地的其他模块,每每这个时候,满满的崩溃啊,今天就是一个...

python设置随机种子实例讲解

对于原生的random模块 import random random.seed(1) 如果不设置,则python根据系统时间自己定一个。 也可以自己根据时间定一个随机种子,如:...