python 使用eval報錯NameError: name ‘null’ is not defined


eval()函數十分強大,它可以把list,tuple,dict和string相互轉化。

最近的項目中用到了eval,使用eval將string轉化成list。其中有一組數據在轉化時報錯:NameError: name ‘null’ is not defined

經過排查,發現string數據中包含‘null’,在轉換時就會報上面的錯誤

data = "[{"id":1,"value":null},{"id":2,"value":"國外"}]" 
result= eval(data)
print(result)

解決方法:

使用replace,將字符串中的null替換掉!

data = "[{"id":1,"value":null},{"id":2,"value":"國外"}]" 
data = data.replace('null', ' ')
result= eval(data)
print(result)

這樣就能正常轉換了

下面介紹一下在數據轉換中,json與eval的區別:

1、json.loads與eval都能將s轉成python中的對象,json.loads將json中的字符串轉成unicode(types.UnicodeType),eval轉成了str(types.StringType)。

2、json不認單引號,json中的字符串需要用雙引號包起來


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM