Python解析JSON数据的基本方法

转自:http://www.jb51.net/article/73450.htm

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。

Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:

  • json.dumps(): 对数据进行编码
  • json.loads()  : 对数据进行解码

Python的json模块提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps() 和 json.loads() , 要比其他序列化函数库如pickle的接口少得多。

下面演示如何将一个Python数据结构转换为JSON:

import json
 
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
 
json_str = json.dumps(data)

下面演示如何将一个JSON编码的字符串转换回一个Python数据结构:

data = json.loads(json_str)

如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:

# Writing JSON data
with open('data.json', 'w') as f:
 json.dump(data, f)
 
# Reading data back
with open('data.json', 'r') as f:
 data = json.load(f)

 

Python 编码为 JSON 类型转换对应表:

PythonJSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

JSON 解码为 Python 类型转换对应表:

JSONPython
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

 

posted @ 2018-01-05 15:58  Ivy_li4258  阅读(1970)  评论(0编辑  收藏  举报