python constant_函式_Python之字串轉字典的小祕密,一起來看看?
阿新 • • 發佈:2021-02-11
技術標籤:python constant_函式
喜歡程式設計,熱愛分享,希望能結交更多志同道合的朋友,一起在學習Python的道路上走得更遠!
起源
需求是將前端傳遞的字串轉化為字典,後端(Python)使用這個字典當做引數體去請求任意介面。
採用的方法是使用json包中的loads函式, 示例如下:
import jsonif __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 -----------> test_json -----------> {'status': 'ok'}Process finished with exit code 0
可以看到輸出是沒什麼大毛病的,但是作為一個嚴謹的人,思考了一下業務應用場景後,決定再測試一下是否能將字串中的整數、浮點數、巢狀字典、陣列、布林值、空值成功轉化。
至於元組和日期型別就放過他吧 : )
探索的過程
探索程式碼:
import jsonif __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)
控制檯輸出:
type -----------> test_json -----------> {'status': {'number': 123, 'float': 123.321, 'list': [1, 2, 3, '1']}} Process finished with exit code 0
嗯,到目前為止都沒啥毛病。
然而
震驚!驚人發現
核心程式碼:
import jsonif __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 -----------> test_json -----------> {'status1': True, 'status2': False, 'status3': None}Process finished with exit code 0
相信聰明的讀者已經發現,json.loads 函式可以 將字串中的true,false, null成功轉化為True,False,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
總結
每段程式碼背後都有小祕密,仔細挖掘就會得到不一樣的樂趣與收穫。
覺得文章還可以的話不妨收藏起來慢慢看,有任何意見或者看法歡迎大家評論!