python 批量将json格式的数据提取成单个json格式

你是不是对成堆的json数据无法下手?想将其拆分成单个json,ok,python简单版分享给你们。

import os
import json
import re
path_file = os.path.dirname(os.path.abspath(__file__))
key_path = os.path.join(path_file, "批量json数据保存路径/video1.json")
 
def subString1(template):   #截取特定字符中间的字符串。
    copy = False
    finished = False
    str = ""
    for s in template:
        if s=='/':
            copy = True
        elif s=='.':
            copy = False
            finished = True
        elif copy:
            str = str+s
        if finished:
            str1=""
            str1+=str
            
    return str1

            
with open(key_path, "r",encoding='utf-8') as fileopen1:
    for line in fileopen1.readlines():
        data=json.loads(line) #json格式转换为列表
        name0=data["source"] #提取特定数据
        name= str(subString1(name0))  #截取字符串中特定字符串
        name=name[10:]  #如果name不满足要求,那需要这句代码提取指定的子串
        
        with open('单个json数据保存路径/{}.json'.format(name),'w',encoding='utf-8') as f:
            f.write(json.dumps(data,indent=4,ensure_ascii=False))
        

以上就是我今天给大家分享的python小技巧,希望对大家有用。

你可能感兴趣的:(python,json,python)