Python之字串轉字典的小秘密,一起來看看?

2021-09-27 06:45:19 字數 2628 閱讀 4855

喜歡程式設計,熱愛分享,希望能結交更多志同道合的朋友,一起在學習python的道路上走得更遠!

需求是將前端傳遞的字串轉化為字典,後端(python)使用這個字典當做引數體去請求任意介面。

採用的方法是使用json包中的loads函式, 示例如下:

import json

if __name__ == '__main__':

test_str = ''

test_json = json.loads(test_str)

print('type -----------> %s' % type(test_json))

print('test_json -----------> %s' % test_json)

執行後控制台輸出如下:

type -----------> test_json -----------> 

process finished with exit code 0

可以看到輸出是沒什麼大毛病的,但是作為乙個嚴謹的人,思考了一下業務應用場景後,決定再測試一下是否能將字串中的整數浮點數巢狀字典陣列布林值空值成功轉化。

至於元組日期型別就放過他吧 : )

探索**:

import json

if __name__ == '__main__':

# 整數+浮點+巢狀字典+陣列 測試

test_str = '}'

test_json = json.loads(test_str)

print('type -----------> %s' % type(test_json))

print('test_json -----------> %s' % test_json)

控制台輸出:

type -----------> test_json -----------> }

process finished with exit code 0

嗯,到目前為止都沒啥毛病。然而

核心**:

import json

if __name__ == '__main__':

# 布林值+空值 測試

test_str = ''

test_json = json.loads(test_str)

print('type -----------> %s' % type(test_json))

print('test_json -----------> %s' % test_json)

控制台輸出:

type -----------> test_json -----------> 

process finished with exit code 0

相信聰明的讀者已經發現,json.loads函式可以 將字串中的truefalse,null成功轉化為truefalsenone

筆者查詢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

每段**背後都有小秘密,仔細挖掘就會得到不一樣的樂趣與收穫。

python 字串轉字典的方法

eval方法轉換字典 user info 使用 eval 卻存在安全性的問題 user eval user info print eval方式 n type user user import json 由於 json 語法規定 陣列或物件之中的字串必須使用雙引號,不能使用單引號 user info1...

Python 字串轉字典(多種方法)

在工作中遇到乙個小問題,需要將乙個python的字串轉為字典,比如字串 user info 我們想把它轉為下面的字典 user dict 有以下幾種方法 1 通過 json 來轉換 import json user info user dict json.loads user info user d...

Python之字串小練

字串 a 3 數字 b 1234 字串可以用單引號表示 c 1 字串也可以用雙引號表示 引導既可以用單引號也可以用雙引號,但是要前後一致 print 列印括號內的內容到控制台 print it s ok.當句子中有單引號時,可以用雙引號,避免語法錯誤 print he said are you ok...