您的位置:首页 > 编程语言 > Python开发

Python读写json文件

2017-04-19 20:47 537 查看
1.JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率),这些特性使JSON成为理想的数据交换语言

2.Python中数据类型与JSON中数据类型转换关系如下表所示:



3.Python中用于序列化的有json和pickle两个模块:

(1)json: 用于字符串和python数据类型间进行转换。

(2)pickle: 用于python特有的类型和python的数据类型间进行转换。

Json和pickle模块都提供了四个功能:dumpsdumploadsload

其中:

(1)dumps把数据类型转换成字符串 ;

(2)dump把数据类型转换成字符串并存储在文件中;

(3)loads把字符串转换成数据类型 ;

(4)load把文件打开从字符串转换成数据类型。

不同之处在于:

(1)json是可以在不同语言之间交换数据的,而pickle只在python之间使用。

(2)json只能序列化最基本的数据类型,josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、)。而pickle可以序列化所有的数据类型,包括类,函数都可以序列化。

4.将Python字典中的数据序列化,并输出到JSON文件中。代码实现如下所示:

# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 19:34:02 2017

@author: zch
"""

import json

test_dict = {"reviewerID": "A1VEELTKS8NLZB", "asin": "616719923X", "reviewerName": "Amazon Customer", "helpful": [0, 0], "reviewText": "Just another flavor of Kit Kat but the taste is unique and a bit different.  The only thing that is bothersome is the price.  I thought it was a bit expensive....", "overall": 4.0, "summary": "Good Taste", "unixReviewTime": 1370044800, "reviewTime": "06 1, 2013"}

print(test_dict)
print(type(test_dict))
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))

with open("record.json","w") as f:
json.dump(test_dict,f)
print("Success!")


运行结果如下图所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python json