使用Python解析JSON的实现示例

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。Python3 中可以使用 json 模块来对 JSON 数据进行编解码,主要包含了下面4个操作函数:

使用Python解析JSON的实现示例

提示:所谓类文件对象指那些具有read()或者 write()方法的对象,例如,f = open(\’a.txt\’,\’r\’),其中的f有read()方法,所以f就是类文件对象。 

在json的编解码过程中,python 的原始类型与JSON类型会相互转换,具体的转化对照如下:

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

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

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

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

操作示例 :

import json
 
data = {
    \'name\': \'pengjunlee\',
    \'age\': 32,
    \'vip\': True,
    \'address\': {\'province\': \'GuangDong\', \'city\': \'ShenZhen\'}
}
# 将 Python 字典类型转换为 JSON 对象
json_str = json.dumps(data)
print(json_str) # 结果 {\"name\": \"pengjunlee\", \"age\": 32, \"vip\": true, \"address\": {\"province\": \"GuangDong\", \"city\": \"ShenZhen\"}}
 
# 将 JSON 对象类型转换为 Python 字典
user_dic = json.loads(json_str)
print(user_dic[\'address\']) # 结果 {\'province\': \'GuangDong\', \'city\': \'ShenZhen\'}
 
# 将 Python 字典直接输出到文件
with open(\'pengjunlee.json\', \'w\', encoding=\'utf-8\') as f:
    json.dump(user_dic, f, ensure_ascii=False, indent=4)
 
# 将类文件对象中的JSON字符串直接转换成 Python 字典
with open(\'pengjunlee.json\', \'r\', encoding=\'utf-8\') as f:
    ret_dic = json.load(f)
    print(type(ret_dic)) # 结果 <class \'dict\'>
    print(ret_dic[\'name\']) # 结果 pengjunlee

注意:使用eval()能够实现简单的字符串和Python类型的转化。 

user1 = eval(\'{\"name\":\"pengjunlee\"}\')
print(user1[\'name\']) # 结果 pengjunlee
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容