Python - Json处理
- 前言:
- 应用场景:
- 基本工具:
- 文件操作:
- 打开文件:
- 写文件:
- 读文件:
- 关闭文件并刷新缓冲区:
- Json字符串和字典转换:
- json.loads():
- json.dumps():
- Json文件和字典转化:
- json.load():
- json.dump():
- 集成上述API为函数:
- 自己开发一个json.dump:
- 扩展:
前言:
Vue框架:
从项目学Vue
OJ算法系列:
神机百炼 - 算法详解
Linux操作系统:
风后奇门 - linux
C++11:
通天箓 - C++11
应用场景:
读取一个json文件,利用其中某些键值对来构建一个新的json文件
- 如获取下列json文件中某几行的键值对,再构建一个json文件
{
"packs": [{
"_id": "1",
"time": 123,
"category": 0,
"current_info": {
"tag": ["timestamp"],
"fps": 60.0,
"time_stamp": 414.514,
"name": "test"
},
"content": {
"core": "service",
"status": 0,
"extraction": "client"
}
}]
}
基本工具:
文件操作:
打开文件:
- open(‘文件路径’, ‘打开方式’):
- w:覆盖写
- r:只读
- wb:二进制写
- rb:二进制读
写文件:
- write(字符串):
字符串中转义字符:
1. \r:切换到当前行的行首列
2. \n:切换到下一行的同一列
file = open('Json文件地址', 'w')
lines = ''
for line in file:
#line自动省略\r\n
lines += line
读文件:
- open()返回一个可迭代对象:
file = open('Json文件地址', 'r')
lines = ''
for line in file:
#line自动省略\r\n
lines += line
关闭文件并刷新缓冲区:
- close:
file.close()
- close()后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法:
file.flush()
Json字符串和字典转换:
json.loads():
- 用于将 字符串 加载为 字典
file = open('Json文件地址', 'r')
lines = ''
for line in file:
lines += line
dic = json.loads(lines)
print(dic)
json.dumps():
- 用于将 字典 写入到 字符串
dic = {'packs': [{'_id': '1', 'time': 123, 'category': 0, 'current_info': {'tag': ['timestamp'], 'fps': 60.0, 'time_stamp': 414.514, 'name': 'test'}, 'content': {'core': 'service', 'status': 0, 'extraction': 'client'}}]}
json_str = json.dumps(dic)
print(json_str)
Json文件和字典转化:
json.load():
- 用于将文件 加载为 字典
dictionary = json.load(open('原本的Json文件地址', 'r'))
print(dictionary)
json.dump():
- 用于将字典 写入到 文件,创建文件使用w模式打开
json.dump(ret, open("新的Json文件地址","w"))
集成上述API为函数:
def func(dictionary,*direct_key, **indirect_key):
ret = {}
for i in direct_key:
ret[i] = dictionary[i]
for i in indirect_key:
ret[i] = {}
print(type(ret), type(ret[i]), i)
for j in indirect_key[i]:
print(j)
ret[i][j] = dictionary[i][j]
return ret
ret = func(json.load('原来的Json文件地址'), '_id', 'end_time', 'frames', ext=['core_cm', 'extraction_cm'], statistics=['parsing_begin', 'parsing_end'])
json.dump(ret, open("新的Json文件地址","w"))
自己开发一个json.dump:
- 简化版,只能接收json最多二重字典,且最终value为str, int, 或float
import os
import json
def isIntOrFloatSeriously(number):
result = False
try:
n = float(number)
if str(number).count('.') != 0 or (n.is_integer() and str(number).count('.') == 0):
result = True
except:
result = False
return result
def func(dictionary,*direct_key, **indirect_key):
amount = len(direct_key) + len(indirect_key)
count = 1
ret = ''
for i in direct_key:
ret += f"\"{i}\": "
if isIntOrFloatSeriously(dictionary[i]) == True :
ret += str(dictionary[i])
else:
ret += "\""+dictionary[i]+"\""
if count < amount:
ret += ","
ret += "\r\n"
count = count + 1
for i in indirect_key:
ret += f"\"{i}\": "+'{\r\n'
inner_count = 1
inner_amount = len(indirect_key[i])
print(inner_amount, indirect_key[i])
for j in indirect_key[i]:
ret += f"\"{j}\": "
if isIntOrFloatSeriously(dictionary[i][j]) == True :
ret += str(dictionary[i][j])
else:
ret += "\""+dictionary[i][j]+"\""
if inner_count < inner_amount:
ret += ","
ret += "\r\n"
inner_count = inner_count + 1
ret += "}"
if count < amount:
ret += ","
ret += "\r\n"
count = count + 1
return ret
file = open('原本的Json文件地址')
lines = ''
for line in file:
lines += line
dic = json.loads(lines)
ret = func(dic["packs"][0], '_id', 'end_time', 'frames', ext=['core_cm', 'extraction_cm'], statistics=['parsing_begin', 'parsing_end'])
file = open('新建的Json文件地址', 'w')
file.write('{\r\n')
file.write(ret)
file.write('}\r\n')
file.close()
扩展:
- Yaml文件格式
- Yaml文件 转化为 字典
- yaml.safe_load():不省略float的.0
- yaml.load():省略float的.0