Python Json序列化与反序列化的示例

# -*- coding: utf-8 -*-

import json
dict = {'name':'zhangsan', 'age':33, 'address':'红星路'}
print'未序列化前的数据类型为:', type(dict)
print'为序列化前的数据:', dict
#对dict进行序列化的处理
dict_xu = json.dumps(dict,ensure_ascii=False)  #直接进行序列化
print'序列化后的数据类型为:', type(dict_xu)
print'序列化后的数据为:', dict_xu

#对dict_xu进行反序列化处理
dict_fan = json.loads(dict_xu)
print'反序列化后的数据类型为:', type(dict_fan)
print'反序列化后的数据为: ', dict_fan

list = ['Apple','Huawei','selenium','java','python']
#把list先序列化,写入到一个文件中
# 两步操作 1步先序列化 列表对象 2步把序列化成的字符串写入文件
json.dump(list, open('e:/test.txt','w'))
r1=open('e:/test.txt','r')
print(r1.read())

#很明显对象都是单引号,而字符串类型都是双引号

# coding: utf-8
import json

list = ['Apple', 'Huawei', 'selenium', 'java', 'python']
# 把list先序列化,写入到一个文件中
# 两步操作 1步先序列化 列表对象 2步把序列化成的字符串写入文件
json.dump(list, open('e:/test.txt', 'w'))
r1 = open('e:/test.txt', 'r')
print(r1.read())
# ------------------------------------------------------------
# 两步操作:1、先读取文件的字符串对象;2、然后反序列化成列表对象
res = json.load(open('e:/test.txt', 'r'))
print (res)
print'数据类型:', type(res)
C:\Python27\python.exe D:/NG_Interface_Test/src/test/test.py
未序列化前的数据类型为: <type 'dict'>
为序列化前的数据: {'age': 33, 'name': 'zhangsan', 'address': '\xe7\xba\xa2\xe6\x98\x9f\xe8\xb7\xaf'}
序列化后的数据类型为: <type 'str'>
序列化后的数据为: {"age": 33, "name": "zhangsan", "address": "红星路"}
反序列化后的数据类型为: <type 'dict'>
反序列化后的数据为:  {u'age': 33, u'name': u'zhangsan', u'address': u'\u7ea2\u661f\u8def'}
["Apple", "Huawei", "selenium", "java", "python"]
["Apple", "Huawei", "selenium", "java", "python"]
[u'Apple', u'Huawei', u'selenium', u'java', u'python']
数据类型: <type 'list'>

https://www.jb51.net/article/134051.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值