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:
- close()後會自動重新整理緩沖區,但有時你需要在關閉前重新整理它,這時就可以使用 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模式打開
內建上述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