Python解析Json格式代码

来自:互联网
时间:2021-09-02
阅读:

由于Python解析Json内容较为复杂,特搬运该脚本:

  • path: 默认路径
  • with_print: 输出格式化内容
  • normal_path_print: 输出当前path
import json
import six
def ppt(obj, path='.', with_print=False, normal_path_print=False):
    base_string = str if six.PY3 else basestring
    obj = json.loads(obj) if isinstance(obj, base_string) else obj
    find_str, find_map = '', ['["%s"]', '[%s]', '%s', '.%s']
    for im in path.split('.'):
        if not im:
            continue
        if isinstance(obj, (list, tuple, base_string)):
            if im.startswith('[') and im.endswith(']'):
                im = im[1:-1]
            if ':' in im:
                slice_default = [0, len(obj), 1]
                obj, quota = obj[slice(
                    *[int(sli) if sli else slice_default[i] for i, sli in
                      enumerate(im.split(':'))])], 1
            else:
                obj, quota = obj[int(im)], 1
        else:
            if im in obj:
                obj, quota = obj[im], 0
            elif im.endswith('()'):
                obj, quota = list(getattr(obj, im[:-2])()), 3
            else:
                if im.isdigit():
                    obj, quota = obj[int(im)], 1
                else:
                    rAIse KeyError(im)
        find_str += find_map[quota] % im
    if with_print:
        print(obj if isinstance(obj, base_string) else
              json.dumps(obj,
                         indent=4,
                         sort_keys=True,
                         ensure_ascii=False))
    if normal_path_print:
        print('get it normally with: <obj>%s' % find_str)
    return obj
演示
测试标准Json内容
import requests
Test_Url = 'https://www.yundun.com/api/V4/stati.data.get'
Test_Code = requests.get(Test_Url).text
print(Test_Code)
print(ppt(Test_Code,'.'))
print(ppt(Test_Code,'.status'))
print(ppt(Test_Code,'.status.code'))
print(ppt(Test_Code,'.status.message'))

以下为输出内容:

{"status":{"code":16149,"message":"没有登录"}}
{'status': {'code': 16149, 'message': '没有登录'}}
{'code': 16149, 'message': '没有登录'}
16149
没有登录
测试多样Json内容
import requests
Test_Url = 'https://www.sojson.com/ps/list.json'
Test_Code = requests.get(Test_Url).text
print(Test_Code)
print(ppt(Test_Code,'.'))
print(ppt(Test_Code,'.b1'))
print(ppt(Test_Code,'.top.[0]'))
print(ppt(Test_Code,'.top.[1]'))
print(ppt(Test_Code,'.top.[:]'))

以下为输出内容:

{"b1":{"url":"https://nima.vip?sojson","red":0,"text":"二维码工具","type":"img","img":"https://cdn.yinshua86.com/file/ps/1341977100","xkey":"banner-1"},"b2":{"url":"https://www.jsjiami.com","red":0,"text":"js加密","type":"img","img":"https://cdn.yinshua86.com/file/ps/1044755494","xkey":"banner-2"},"indexRight":{"url":"https://www.upyun.com/?from=sojson.com","red":0,"text":"又拍云","type":"img","img":"https://nos.netease.com/yyimgs/LwRTCYEAX2jKBAIvvGU61Q==/109951164031881717","xkey":"index-right-275x130"},"top":[{"url":"https://www.henghost.com/act/202002/202002.html?s=zz&sojson","red":1,"text":"香港/美国服务器,限量2.5折","type":"text","img":"","xkey":"top-text"},{"url":"https://console.upyun.com/register/?invite=H1Z6578p-","red":0,"text":"又拍云","type":"text","img":"","xkey":"top-text"}]}
{'b1': {'url': 'https://nima.vip?sojson', 'red': 0, 'text': '二维码工具', 'type': 'img', 'img': 'https://cdn.yinshua86.com/file/ps/1341977100', 'xkey': 'banner-1'}, 'b2': {'url': 'https://www.jsjiami.com', 'red': 0, 'text': 'js加密', 'type': 'img', 'img': 'https://cdn.yinshua86.com/file/ps/1044755494', 'xkey': 'banner-2'}, 'indexRight': {'url': 'https://www.upyun.com/?from=sojson.com', 'red': 0, 'text': '又拍云', 'type': 'img', 'img': 'https://nos.netease.com/yyimgs/LwRTCYEAX2jKBAIvvGU61Q==/109951164031881717', 'xkey': 'index-right-275x130'}, 'top': [{'url': 'https://www.henghost.com/act/202002/202002.html?s=zz&sojson', 'red': 1, 'text': '香港/美国服务器,限量2.5折', 'type': 'text', 'img': '', 'xkey': 'top-text'}, {'url': 'https://console.upyun.com/register/?invite=H1Z6578p-', 'red': 0, 'text': '又拍云', 'type': 'text', 'img': '', 'xkey': 'top-text'}]}
{'url': 'https://nima.vip?sojson', 'red': 0, 'text': '二维码工具', 'type': 'img', 'img': 'https://cdn.yinshua86.com/file/ps/1341977100', 'xkey': 'banner-1'}
{'url': 'https://www.henghost.com/act/202002/202002.html?s=zz&sojson', 'red': 1, 'text': '香港/美国服务器,限量2.5折', 'type': 'text', 'img': '', 'xkey': 'top-text'}
{'url': 'https://console.upyun.com/register/?invite=H1Z6578p-', 'red': 0, 'text': '又拍云', 'type': 'text', 'img': '', 'xkey': 'top-text'}
[{'url': 'https://www.henghost.com/act/202002/202002.html?s=zz&sojson', 'red': 1, 'text': '香港/美国服务器,限量2.5折', 'type': 'text', 'img': '', 'xkey': 'top-text'}, {'url': 'https://console.upyun.com/register/?invite=H1Z6578p-', 'red': 0, 'text': '又拍云', 'type': 'text', 'img': '', 'xkey': 'top-text'}]
返回顶部
顶部