python3.x 基础四:json与pickple
- 每次打开一个文件,只dump1次
- json.dump(dump的内容,文件句柄)
- json.load(文件句柄)
- json可以处理列表/字典/字符串等简单数据类型,但是不能处理复杂的数据类型,如函数的内存地址
- 不同语言间都可以用json文件
import json
dict1={'name':'alex','age':22,'salary':1000}
print('dict is %s\ndumping dict to file...' % (dict1))
fd = open('fd.txt','w',encoding='utf-8')
# with open('fd.txt','w',encoding='utf-8') as fd:
# json.dump(dict1,fd)
dict2={'name':'oldboy','age':32,'salary':2000}
# with open('fd.txt','w',encoding='utf-8') as fd:
# json.dump(dict2,fd)
json.dump(dict1,fd)
fd.close()
# json.dump(dict2,fd)
fd = open('fd.txt','r',encoding='utf-8')
print('load content from file...')
print(json.load(fd))
fd.close()
output:
dict is {'age': 22, 'salary': 1000, 'name': 'alex'}
dumping dict to file...
load content from file...
{'age': 22, 'salary': 1000, 'name': 'alex'}
dumping dict to file...
import json
dict1={}
def func():
print('in the func')
dict1['name']=func
fd = open('fdw.txt','w',encoding='utf-8')
print('dumping dict to file...' % (dict1))
json.dumps(dict1,fd)
fd.close()
error:
TypeError: <function func at 0x7f0828c68488> is not JSON serializable
- pickle能处理python所有的数据类型
import pickle
dict1={}
def func():
print('in the func')
dict1['name']=func
fd = open('fdw.txt','wb')
print('dumping dict to file... %s' % (dict1))
pickle.dump(dict1,fd)
fd.close()
fd = open('fdw.txt','rb')
print(pickle.load(fd))
fd.close()
output:
dumping dict to file... {'name': <function func at 0x7fa1904d4488>}
{'name': <function func at 0x7fa1904d4488>}
dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Serialize ``obj`` to a JSON formatted ``str``.
- 将一个对象转换成json格式的字符串
loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
- 将一个json格式的对象反序列成python对象
import json
l1 = ["alex", 123, "eric"]
l2 = ["alex", 123, 'eric']
s1 = """ ["alex", 123, "eric"] """
s2 = """ ["alex", 123, 'eric'] """
print(json.dumps(l1),type(json.dumps(l1))) # list to str
print(json.dumps(l2),type(json.dumps(l2))) # list to str
print(json.dumps(s1),type(json.dumps(s1))) # still str
print(json.dumps(s2),type(json.dumps(s2))) # still str # 四个正确
# print(json.loads(l1)) # json格式需要字符串,这是列表
# print(json.loads(l2)) # 同上
print(json.loads(s1),type(json.loads(s1))) # str to list,json格式需要双引号
# print(json.loads(s2)) # 格式错误,有单引号 dict1={}
dict1["name"]="xxx"
print(json.dumps(dict1),type(json.dumps(dict1)))
# str1='''dict1["name"]="xxx"'''
# print(json.loads(str)) l = ['iplaypython', [1, 2, 3], {'name':'xiaoming'}]
encoded_json = json.dumps(l)
print(encoded_json,type(encoded_json))
decode_json = json.loads(encoded_json)
print(decode_json,type(decode_json)) 输出
["alex", 123, "eric"] <class 'str'>
["alex", 123, "eric"] <class 'str'>
" [\"alex\", 123, \"eric\"] " <class 'str'>
" [\"alex\", 123, 'eric'] " <class 'str'>
['alex', 123, 'eric'] <class 'list'>
{"name": "xxx"} <class 'str'>
["iplaypython", [1, 2, 3], {"name": "xiaoming"}] <class 'str'>
['iplaypython', [1, 2, 3], {'name': 'xiaoming'}] <class 'list'>
python3.x 基础四:json与pickple的更多相关文章
- python3.x 基础四:目录获取及目录规范
1.获取目录 import os,sys print('程序文件运行相对位置>>',os.path.abspath(__file__)) print('程序文件上级绝对目录>> ...
- python3.x 基础四:生成器与迭代器
1.预先存值到内存,调用之前已经占用了内存,不管用与不用,都占用内存 >>> a=[1,2,3,4,5] >>> type(a) <class 'list'& ...
- Python 基础 四 面向对象杂谈
Python 基础 四 面向对象杂谈 一.isinstance(obj,cls) 与issubcalss(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls ...
- Python全栈开发【基础四】
Python全栈开发[基础四] 本节内容: 匿名函数(lambda) 函数式编程(map,filter,reduce) 文件处理 迭代器 三元表达式 列表解析与生成器表达式 生成器 匿名函数 lamb ...
- Bootstrap<基础四> 代码
Bootstrap 允许您以两种方式显示代码: 第一种是 <code> 标签.如果您想要内联显示代码,那么您应该使用 <code> 标签. 第二种是 <pre> 标 ...
- 从零开始学习PYTHON3讲义(四)让程序更友好
<从零开始PYTHON3>第四讲 先看看上一讲的练习答案. 程序完成的是功能,功能来自于"程序需求"("需求"这个词忘记了什么意思的去复习一下第二讲 ...
- C#_02.13_基础四_.NET方法
C#_02.13_基础四_.NET方法 一.方法概述: 方法是一块具有名称的代码.可以通过方法进行调用而在别的地方执行,也可以把数据传入方法并接受数据输出. 二.方法的结构: 方法头 AND 方法 ...
- Java基础-处理json字符串解析案例
Java基础-处理json字符串解析案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 作为一名开发人员,想必大家或多或少都有接触到XML文件,XML全称为“extensible ...
- python3字典:获取json响应值来进行断言的用法详解
在Python中我们做接口经常用到一些json的返回值我们常把他转化为字典,在前面的python数据类型详解(全面)中已经谈到对字典的的一些操作,今天我们就获取json返回值之后,然后转化为字典后的获 ...
随机推荐
- [Windows] Diskpart Scripts and Examples
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/diskpart-scripts-and ...
- Android Studio SVN配置忽略文件
1.用Android Studio创建一个项目,会在根目录和Module目录下自动生成.gitignore文件,貌似是Git的配置文件,和SVN没有关系. 2.打开Setting-Version Co ...
- Salesforce吹嘘无代码开发,不用费脑子的人工智能
Salesforce在星期四举办的Dreamforce '16大会上,开发人员主题演讲可谓面面俱到--听众被舞台包围了,而不是远远地坐在观众席. 这是符合该公司在六月份第一次的开发者大会Trailhe ...
- SQL Server 字段和对应的说明操作(SQL Server 2005 +)
为什么80%的码农都做不了架构师?>>> 添加说明 EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value ...
- .user.ini 无法修改/删除 怎么办?
首先 了解chattr命令: Linux chattr命令用于改变文件属性. 这项指令可改变存放在ext2文件系统上的文件或目录属性,这些属性共有以下8种模式: a:让文件或目录仅供附加用途.b:不更 ...
- 信息竞赛进阶指南--KMP算法(模板)
next[1] = 0; for (int i = 2, j = 0; i <= n; i++) { while (j > 0 && a[i] != a[j+1]) j = ...
- Codeforce-Ozon Tech Challenge 2020-C. Kuroni and Impossible Calculation(鸽笼原理)
To become the king of Codeforces, Kuroni has to solve the following problem. He is given n numbers a ...
- UVA-1 #1. A + B Problem
给你两个数 aa 和 bb,请输出他们的和. 输入格式 一行,两个用空格隔开的整数 aa 和 bb. 输出格式 一个整数,表示 a+ba+b. 样例一 input 2 3 output 5 限制与约定 ...
- css的属性选择器
语法说明: 属性选择器需要将对应属性放入到 方括号中 [ ] ,其中包含属性名,标识符(* $ ~ ^ |) 使用说明: [attribute] 例如 [target] 表示 选择带有 targe ...
- 工具类CountDownLatch的应用---百米赛跑案例
package com.aj.thread; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Execu ...