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. greendao的基本操作

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

  2. 编程技巧 - malloc()与free()

    1.要节省ram资源,可以使用malloc()动态申请内存,使用完再用free()释放掉,free()释放的是指针指向的内存空间,而不是指针. 2.如果某个大数组要在两个函数中使用,可以先定义一个全局 ...

  3. php-instanceof运算符

    1.关于 instanceof 的一些基本概念 1).instanceof 用于确定一个PHP变量是否属于某一类class的实例: <?php class MyClass { } class N ...

  4. JAVA 成员访问权限修饰符

    修饰符         类内部     package内         子类         其他 public             允许         允许                 ...

  5. 【BZOJ4657】tower [网络流]

    炮塔 Time Limit: 10 Sec  Memory Limit: 256 MB Description Input Output 一行一个整数表示答案. Sample Input 4 5 0 ...

  6. HDU 4320 Arcane Numbers 1 (数论)

    A - Arcane Numbers 1 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64 ...

  7. 在ubuntu 上面安装ubuntu touch 模拟器

    Canonical 公司已经发布了一个运行着Unity8和Mir的Ubuntu Touch模拟器.虽然有一些bug,例如在64位的系统上会使系统崩溃,但我们相信这些都会被一 一修复,这篇文章将教大家如 ...

  8. 会话Cookie

    Cookie分为会话Cookie和本地Cookie两种 之前一直理解的是会话Cookie不在本地文件存储,只存储于内存,而本地Cookie因为设置了expire过期时间需要在本地存储 下面是白帽子讲W ...

  9. Python学习笔记 - day2 - PyCharm的基本使用

    什么是IDE 开始学习的小白同学,一看到这三个字母应该是懵逼的,那么我们一点一点来说. 既然学习Python语言我们就需要写代码,那么代码写在哪里呢? 在记事本里写 在word文档里写 在sublim ...

  10. pyhton发送邮件

    # import smtplib # from email.mime.text import MIMEText # _user = "你的qq邮箱" # _pwd = " ...