对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设计】。

相关文章

softmax及python实现过程解析

softmax及python实现过程解析

相对于自适应神经网络、感知器,softmax巧妙低使用简单的方法来实现多分类问题。 功能上,完成从N维向量到M维向量的映射 输出的结果范围是[0, 1],对于一个sample的...

Python自动化运维之IP地址处理模块详解

实用的IP地址处理模块IPy 在IP地址规划中,涉及到计算大量的IP地址,包括网段、网络掩码、广播地址、子网数、IP类型等 别担心,Ipy模块拯救你。Ipy模块可以很好的辅助我们高效的...

Django Form and ModelForm的区别与使用

Form介绍 在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来。 与此同时我们在好多场景下都需要对用户的输入做校验,比如校验...

Python模块搜索概念介绍及模块安装方法介绍

Python模块搜索概念介绍及模块安装方法介绍

【import模块】 和C中的#include不同,Python中的import语句并不是简单的把一个文件插入另外一个文件。 导入其实是运行时的运算,程序第一次导入指定文件时,会执行以下...

Python 实现某个功能每隔一段时间被执行一次的功能方法

本人在做项目的时候遇到一个问题: 某个函数需要在每个小时的 3 分钟时候被执行一次,我希望我 15:45 启动程序,过了18 分钟在 16:03 这个函数被执行一次,下一次过 60 分钟...