Python之字符串轉字典的小祕密

起源

需求是將前端傳遞的字符串轉化爲字典,後端(Python)使用這個字典當作參數體去請求任意接口。前端

筆者採用的方法是使用json包中的loads函數, 示例以下:json

import json

if __name__ == '__main__':
    test_str = '{"status": "ok"}'
    test_json = json.loads(test_str)
    print('type -----------> %s' % type(test_json))
    print('test_json -----------> %s' % test_json)
複製代碼

運行後控制檯輸出以下:後端

type -----------> <class 'dict'>
test_json -----------> {'status': 'ok'}

Process finished with exit code 0
複製代碼

能夠看到輸出是沒什麼大毛病的,可是做爲一個嚴謹的人,思考了一下業務應用場景後,決定再測試一下是否能將字符串中的整數浮點數嵌套字典數組布爾值空值成功轉化。數組

至於元組日期類型就放過他吧 : )函數

探索的過程

探索代碼:測試

import json

if __name__ == '__main__':
    # 整數+浮點+嵌套字典+數組 測試
    test_str = '{"status": {"number": 123, "float": 123.321, "list": [1,2,3, "1"]}}'
    test_json = json.loads(test_str)
    print('type -----------> %s' % type(test_json))
    print('test_json -----------> %s' % test_json)
複製代碼

控制檯輸出:spa

type -----------> <class 'dict'>
    test_json -----------> {'status': {'number': 123, 'float': 123.321, 'list': [1, 2, 3, '1']}}
    
    Process finished with exit code 0
複製代碼

嗯,到目前爲止都沒啥毛病。3d

然而code

震驚!驚人發現

核心代碼:cdn

import json

if __name__ == '__main__':
    # 布爾值+空值 測試
    test_str = '{"status1": true, "status2": false, "status3": null}'
    test_json = json.loads(test_str)
    print('type -----------> %s' % type(test_json))
    print('test_json -----------> %s' % test_json)
複製代碼

控制檯輸出:

type -----------> <class 'dict'>
test_json -----------> {'status1': True, 'status2': False, 'status3': None}

Process finished with exit code 0
複製代碼

相信聰明的讀者已經發現,json.loads 函數能夠 將字符串中的truefalse, null成功轉化爲TrueFalse, None

筆者查找 json.loads 函數源碼 (Ctrl + B 已經按爛) 後,發現了這一段代碼:

elif nextchar == 'n' and string[idx:idx + 4] == 'null':
        return None, idx + 4
    elif nextchar == 't' and string[idx:idx + 4] == 'true':
        return True, idx + 4
    elif nextchar == 'f' and string[idx:idx + 5] == 'false':
        return False, idx + 5
複製代碼

這,這代碼,真硬氣

往下翻還有驚喜哦:

elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
        return parse_constant('NaN'), idx + 3
    elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
        return parse_constant('Infinity'), idx + 8
    elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
        return parse_constant('-Infinity'), idx + 9
複製代碼

總結

每段代碼背後都有小祕密,仔細挖掘就會獲得不同的樂趣與收穫。

正所謂 博客驅動開發,開發只是爲了更好的 寫做 !

歡迎你們掃碼關注個人公衆號「智能自動化測試」,回覆:測試進階教程,便可免費得到 進階教程 ~

祝你們生活愉快,事事順心~

--泰斯特
                                                                                                    2019-5-24
複製代碼
相關文章
相關標籤/搜索