Python中JSON結(jié)構(gòu)數(shù)據(jù)的高效增刪改操作
1 簡(jiǎn)介
在上一期文章中我們一起學(xué)習(xí)了在Python中如何使用jsonpath庫(kù),對(duì)JSON格式數(shù)據(jù)結(jié)構(gòu)進(jìn)行常規(guī)的節(jié)點(diǎn)條件查詢(xún),可以滿(mǎn)足日常許多的數(shù)據(jù)處理需求。
而在上一期結(jié)尾處,我提到了還有其他JSONPath功能相關(guān)的進(jìn)階Python庫(kù),在今天的文章中,我就將帶大家學(xué)習(xí)更加高級(jí)的JSON數(shù)據(jù)處理方式。
2 基于jsonpath-ng的進(jìn)階JSON數(shù)據(jù)處理方法
jsonpath-ng是一個(gè)功能強(qiáng)大的Python庫(kù),它整合了jsonpath-rw、jsonpath-rw-ext等第三方JSONPath拓展庫(kù)的實(shí)用功能,使得我們可以基于JSONPath語(yǔ)法,實(shí)現(xiàn)更多操縱JSON數(shù)據(jù)的功能,而不只是查詢(xún)數(shù)據(jù)而已,使用pip install jsonpath-ng進(jìn)行安裝:
2.1 JSON數(shù)據(jù)的增刪改
jsonpath-ng中設(shè)計(jì)了一些方法,可以幫助我們實(shí)現(xiàn)對(duì)現(xiàn)有JSON數(shù)據(jù)的增刪改操作,首先我們來(lái)學(xué)習(xí)jsonpath-ng中如何定義JSONPath模式,并將其運(yùn)用到對(duì)數(shù)據(jù)的匹配上,依然以上篇文章的數(shù)據(jù)為例:
- import json
- from jsonpath_ng import parse
- # 讀入示例json數(shù)據(jù)
- with open('json示例.json', encoding='utf-8') as j:
- demo_json = json.loads(j.read())
- # 構(gòu)造指定JSONPath模式對(duì)應(yīng)的解析器
- parser = parse('$..paths..steps[*].duration')
- # 利用解析器的find方法找到目標(biāo)數(shù)據(jù)中所有滿(mǎn)足條件的節(jié)點(diǎn)
- matches = parser.find(demo_json)
- # 利用value屬性取得對(duì)應(yīng)匹配結(jié)果的值
- matches[0].value
而基于上面產(chǎn)生的一些對(duì)象我們就可以實(shí)現(xiàn)對(duì)JSON數(shù)據(jù)的增刪改:
2.1.1 對(duì)JSON數(shù)據(jù)進(jìn)行增操作
在jsonpath-ng中對(duì)JSON數(shù)據(jù)添加節(jié)點(diǎn),思想是先構(gòu)造對(duì)「原先不存在」的節(jié)點(diǎn)進(jìn)行匹配的解析器對(duì)象,利用find_or_create方法處理原始JSON數(shù)據(jù):
- # 構(gòu)造示例數(shù)據(jù)
- demo_json = {
- 'level1': [
- {
- 'level2': {}
- },
- {
- 'level2': {
- 'level3': 12
- }
- }
- ]
- }
- # 構(gòu)造規(guī)則解釋器,所有除去最后一層節(jié)點(diǎn)規(guī)則外可以匹配到的節(jié)點(diǎn)
- # 都屬于合法匹配結(jié)果,會(huì)在匹配結(jié)果列表中出現(xiàn)
- parser = parse('level1[*].level2.level3')
- matches = parser.find_or_create(demo_json)
- demo_json
在find_or_create操作之后,demo_json就被修改成下面的結(jié)果:
接下來(lái)的事情就很簡(jiǎn)單了,只需要在matches結(jié)果中進(jìn)行遍歷,遇到value屬性為{}的,就運(yùn)用full_path.update_or_create()方法對(duì)原始JSON數(shù)據(jù)進(jìn)行更新即可,比如這里我們填充999:
- for match in matches:
- if match.value == {}:
- # 更新原始輸入的JSON數(shù)據(jù)
- match.full_path.update_or_create(demo_json, 999)
- demo_json
2.1.2 對(duì)JSON數(shù)據(jù)進(jìn)行刪操作
當(dāng)我們希望對(duì)JSON數(shù)據(jù)中指定JSONPath規(guī)則的節(jié)點(diǎn)予以刪除時(shí),可以使用到parse對(duì)象的filter()方法傳入lambda函數(shù),在lambda函數(shù)中進(jìn)行條件判斷,返回的即為刪除指定節(jié)點(diǎn)之后的輸入數(shù)據(jù)。
以上一步「增」操作后得到的demo_json為例,我們來(lái)對(duì)其level1[*].level2.level3值為999的予以過(guò)濾:
- parser = parse('level1[*].level2.level3')
- # 過(guò)濾 level1[*].level2.level3 規(guī)則下值為 999 的節(jié)點(diǎn)
- parser.filter(lambda x: x == 999, demo_json)
- demo_json
可以看到結(jié)果正是我們所預(yù)期的:
2.1.3 對(duì)JSON數(shù)據(jù)進(jìn)行改操作
對(duì)JSON數(shù)據(jù)中的指定節(jié)點(diǎn)進(jìn)行改操作非常的簡(jiǎn)單,只需要使用parse對(duì)象的update或update_or_create方法即可,使用效果的區(qū)別如下所示,輕輕松松就可以完成兩種策略下的節(jié)點(diǎn)更新操作😋:
jsonpath-ng中還有一些豐富的功能,這里就不再贅述,感興趣的讀者朋友可以前往https://github.com/h2non/jsonpath-ng查看。