python 编程开发 —— JSON 数据处理

文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。


笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者:Aliven888

1、简述

  JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。

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

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

  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

2、Json 操作实例

#!/usr/bin/python3.8.8
# -*- coding: utf-8 -*-

import json

# Pyhon 字典类型转化成 JSON 对象
data1 = {
    
    
	        "no":1,
	        "name":"Aliven",
	        "score":92.9
        }

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


# 将 Json 对象转化成 Python 字典
data2 = json.loads(json_str)
print("data2['name'] : ", data2['name'])
print("data2['score'] : ", data2['score'])

# ================== 输出结果 ==================
原始数据: {
    
    'no': 1, 'name': 'Aliven', 'score': 92.9}
JSON 对象: {
    
    "no": 1, "name": "Aliven", "score": 92.9}
data2['name'] :  Aliven
data2['score'] :  92.9

  如果你要处理的是文件而不是字符串,你可以使用 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)

猜你喜欢

转载自blog.csdn.net/Aliven888/article/details/115432331
今日推荐