【效率工具】mac端基于Alfred和python的json字符串重解析工具,完美解析json字符串

1.背景

在抓取头条App的接口的时候,发现有的接口从Charles直接复制到谷歌插件JSON-handle之后可读性非常差,如下所示。以content字段为例,没有被正确的json格式解析。

json优化前

https://www.bilibili.com/video/BV1Q54y1v7qV/

2.操作流程

command+c复制待解析字符串 - Alfred唤起python脚本 - python获取剪贴板内容 - json重解析 - 结果写入剪贴板 - command+v使用

如下所示

alfred版json重解析

https://www.bilibili.com/video/BV1eh411Z7AD/

3.关键代码

import json
import pyperclip

def getJsonDict(jsonData: dict):
    if type(jsonData) != dict:
        return
    for i in jsonData.keys():
        try:
            jsonData[i] = json.loads(jsonData[i])
            getJsonDict(jsonData[i])
        except TypeError:

            if (type(jsonData[i])) == dict:
                getJsonDict(jsonData[i])

            if (type(jsonData[i])) == list:
                for index in range(len(jsonData[i])):
                    try:
                        jsonData[i][index] = json.loads(jsonData[i][index])
                        getJsonDict(jsonData[i][index])
                    except TypeError:
                        if (type(jsonData[i][index])) == dict:
                            getJsonDict(jsonData[i][index])
                    except json.decoder.JSONDecodeError:
                        if (type(jsonData[i][index])) == dict:
                            getJsonDict(jsonData[i][index])

        except json.decoder.JSONDecodeError:

            if (type(jsonData[i])) == dict:
                getJsonDict(jsonData[i])

            if (type(jsonData[i])) == list:
                for index in range(len(jsonData[i])):
                    try:
                        jsonData[i][index] = json.loads(jsonData[i][index])
                        getJsonDict(jsonData[i][index])
                    except TypeError:
                        if (type(jsonData[i][index])) == dict:
                            getJsonDict(jsonData[i][index])
                    except json.decoder.JSONDecodeError:
                        if (type(jsonData[i][index])) == dict:
                            getJsonDict(jsonData[i][index])

if __name__ == '__main__':
    jsonData = json.loads(pyperclip.paste())
    getJsonDict(jsonData)
    pyperclip.copy(json.dumps(jsonData))
    items = {"items": []}
    template = {
        "title": "",
        "subtitle": "",
        "arg": ""
    }
    template["title"] = "success"
    template["subtitle"] = "success"
    template["arg"] = "success"
    items["items"].append(template);
    print(json.dumps(items))

4.Alfred的workflow文件

评论留下邮箱发你

你可能感兴趣的:(【效率工具】mac端基于Alfred和python的json字符串重解析工具,完美解析json字符串)