Python3 JSON处理

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

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

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

 

 

 

 

 

 

 

 

#!/usr/bin/python3

import json

# Python 字典类型转换为 JSON 对象
data = {
    'no' : 1,
    'name' : 'Runoob',
    'url' : 'http://www.runoob.com'
}

json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)

输出结果为:

Python 原始数据: {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON 对象: {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}

通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。

接着以上实例,我们可以将一个JSON编码的字符串转换回一个Python数据结构:

# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

输出结果为:

Python 原始数据: {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON 对象: {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com

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

 写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data, f)

# 读取数据
with open('data.json', 'r') as f:
    data = json.load(f)

 

Changed in version 3.6: All parameters are now keyword-only.

default(o):

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return json.JSONEncoder.default(self, o)

encode(o):

json.JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'

iterencode(o):

for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

 

posted on 2018-03-26 10:53  明日边缘-道法自然  阅读(3019)  评论(0编辑  收藏  举报