Python之dict(或对象)与json之间的互相转化

在Python语言中,json数据与dict字典以及对象之间的转化,是必不可少的操作。

在Python中自带json库。通过import json导入。

在json模块有2个方法,

  • loads():将json数据转化成dict数据
  • dumps():将dict数据转化成json数据
  • load():读取json文件数据,转成dict数据
  • dump():将dict数据转化成json数据后写入json文件

下面是具体的示例:

dict字典转json数据

import json

def dict_to_json():
dict = {}
dict['name'] = 'many'
dict['age'] = 10
dict['sex'] = 'male'
print(dict) # 输出:{'name': 'many', 'age': 10, 'sex': 'male'}
j = json.dumps(dict)
print(j) # 输出:{"name": "many", "age": 10, "sex": "male"} if __name__ == '__main__':
dict_to_json()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

对象转json数据

import json

def obj_to_json():
stu = Student('007', '007', 28, 'male', '13000000000', '123@qq.com')
print(type(stu)) # <class 'json_test.student.Student'>
stu = stu.__dict__ # 将对象转成dict字典
print(type(stu)) # <class 'dict'>
print(stu) # {'id': '007', 'name': '007', 'age': 28, 'sex': 'male', 'phone': '13000000000', 'email': '123@qq.com'}
j = json.dumps(obj=stu)
print(j) # {"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "123@qq.com"} if __name__ == '__main__':
obj_to_json()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

json数据转成dict字典

import json

def json_to_dict():
j = '{"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "123@qq.com"}'
dict = json.loads(s=j)
print(dict) # {'id': '007', 'name': '007', 'age': 28, 'sex': 'male', 'phone': '13000000000', 'email': '123@qq.com'} if __name__ == '__main__':
json_to_dict()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

json数据转成对象

import json

def json_to_obj():
j = '{"id": "007", "name": "007", "age": 28, "sex": "male", "phone": "13000000000", "email": "123@qq.com"}'
dict = json.loads(s=j)
stu = Student()
stu.__dict__ = dict
print('id: ' + stu.id + ' name: ' + stu.name + ' age: ' + str(stu.age) + ' sex: ' + str(
stu.sex) + ' phone: ' + stu.phone + ' email: ' + stu.email) # id: 007 name: 007 age: 28 sex: male phone: 13000000000 email: 123@qq.com if __name__ == '__main__':
json_to_obj()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

json的load()dump()方法的使用

  • dump()方法的使用

import json def dict_to_json_write_file():
dict = {}
dict['name'] = 'many'
dict['age'] = 10
dict['sex'] = 'male'
print(dict) # {'name': 'many', 'age': 10, 'sex': 'male'}
with open('1.json', 'w') as f:
json.dump(dict, f) # 会在目录下生成一个1.json的文件,文件内容是dict数据转成的json数据 if __name__ == '__main__':
dict_to_json_write_file()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • load()的使用
import json

def json_file_to_dict():
with open('1.json', 'r') as f:
dict = json.load(fp=f)
print(dict) # {'name': 'many', 'age': 10, 'sex': 'male'} if __name__ == '__main__':
json_file_to_dict()

python中json与dict之间转换的更多相关文章

  1. Python 中 JSON和dict的转换,json的使用

    一. 基础语法 在Python 的 json库中,共有四个方法.分别是: json.load() # 从文件中加载 json.loads() # 数据中加载 json.dump() # 转存到文件 j ...

  2. 002、Python中json字符串与字典转换

    1.测试用例文件TestCase.xlsx 2.编写Python文件进行读取 #!/usr/bin/env python # -*- coding:utf-8 -*- import time impo ...

  3. Python中xml和dict格式转换

    在做接口自动化的时候,请求数据之前都是JSON格式的,Python有自带的包来解决.最近在做APP的接口,遇到XML格式的请求数据,费了很大劲来解决,解决方式是:接口文档拿到的是XML,在线转化为js ...

  4. python 中json和字符串互相转换

      string =" {  "status": "error",  "messages": ["Could not f ...

  5. python中unicode, hex, bin之间的转换

    python中unicode, hex, bin之间的转换 背景 在smb中有个feature change notify, 需要改动文件权限dacl,然后确认是否有收到notify.一直得不到这个d ...

  6. Python中json的简单读写操作

    Python中json的简单读写操作 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的 ...

  7. python中json格式数据输出实现方式

    python中json格式数据输出实现方式 主要使用json模块,直接导入import json即可. 小例子如下: #coding=UTF-8 import json info={} info[&q ...

  8. python中,== 与 is 之间区别

    在python中,== 与 is 之间既有区别,又有联系,本文将通过实际代码的演示,力争能够帮助读到这篇文章的朋友以最短的时间理清二者的关系,并深刻理解它们在内存中的实现机制. 扯淡的话不多说,下面马 ...

  9. Python中字符串与字节之间相互转换

    Python中字符串与字节之间相互转换 ​ a = b"Hello, world!" # bytes object b = "Hello, world!" # ...

随机推荐

  1. Codeforces Round #526 (Div. 2) C. The Fair Nut and String

    C. The Fair Nut and String 题目链接:https://codeforces.com/contest/1084/problem/C 题意: 给出一个字符串,找出都为a的子序列( ...

  2. greendao的基本操作

    1.先配置项目的builder.gradle // Top-level build file where you can add configuration options common to all ...

  3. region xx not deployed on any region server

    ERROR: Region { meta => month_hotstatic,860010-2288000000_201405_5_exit_00000047486,1400144486405 ...

  4. MAVEN 编译打包测试 指定本地jar

    转载自:http://penuel.iteye.com/blog/1766102 maven对于互联网开发,进行版本管理有着不可或缺的作用;  而经常开发的程序猿直接联调或者依赖未上线或deploy的 ...

  5. linux+GraphicsMagick 安装

    转摘自:http://blog.csdn.net/fhqsse220/article/details/12995763 GraphicsMagick 安装 下载软件:download:ftp://ft ...

  6. hdu 4506 小明系列故事——师兄帮帮忙

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4506 题目大意:找规律,判断k的t次幂前面的系数. #include <iostream> ...

  7. hdu 2016 数据的交换输出

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2016 题目大意:把最小的和第一个交换并输出.注意格式哦! #include <stdio.h&g ...

  8. Quorum一致性协议

    Quorum一致性协议 一个分布式数据库系统中通常是一系列密切关联的操作组成完整的系统. 分布式系统最基本的要保证一致性, 分区性通常是无法避免的, 在这种情况下尽力通过软件协议做到最大可用性. 根据 ...

  9. Spring MVC的静态和动态概念

    MVC模式: 图释:用户请求通过HTTP协议到达Front controller,Front controller把请求送给Controller,Controller了解业务逻辑细节并且调用业务逻辑数 ...

  10. 6.memcached缓存系统

    1.memcached的安装和参数 memcached缓存系统一般还是部署在linux服务器上,所以这里只介绍linux上memcache的安装 首先切换到root用户,然后apt-get insta ...