对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中enumerate函数遍历元素用法分析

本文实例讲述了python中enumerate函数遍历元素用法。分享给大家供大家参考,具体如下: enumerate函数用于遍历序列中的元素以及它们的下标 示例代码如下: i = 0...

python实现复制文件到指定目录

这几天在做一个数据集,由于不是很熟悉Linux下的命令,所以特地用了强大的python来做。我之前有一个数据集但是我只要里面名称带有composite和normals的图片,所以找了网上...

Appium+python自动化怎么查看程序所占端口号和IP

Appium+python自动化怎么查看程序所占端口号和IP

简介 这篇博文和分类看似没有多大关系,但是也是从上一篇衍生出来的产物,因为涉及到 FQ工具 Lantern ,就算是给关注和支持的小伙伴们拓展一下眼界和知识面。而且好多人都阅读了上一篇...

python使用xlrd模块读写Excel文件的方法

本文实例讲述了python使用xlrd模块读写Excel文件的方法。分享给大家供大家参考。具体如下: 一、安装xlrd模块 到python官网下载http://pypi.python....

python BlockingScheduler定时任务及其他方式的实现

本文介绍了python BlockingScheduler定时任务及其他方式的实现,具体如下: #BlockingScheduler定时任务 from apscheduler.sc...