Python中用eval將字符串轉換為字典時候出錯:NameError: name ‘null’ is not defined的解決方法


這兩天在用python調用接口時,因為接口返回的是str類型的數據,形如:

因為這樣的str類似字典,所以我想把它轉為字典以便處理,使用的是eval來進行轉換,如下:

 

  1.  
    <pre name= "code" class="python">a='{"errno":0,"errmsg":null,"unassigned":0,"total":0,"list":null}'
  2.  
    a=eval(a)
  3.  
    print type(a)

 

 

 
        

結果出現錯誤如下:NameError: name ‘null’ is not defined

 

查詢資料發現,python無法處理null這樣的字符串,所以報錯。解決方法有兩個:

一、把null轉換為python可以接受的字符,例如空字符串

如:

 

  1.  
    global null
  2.  
    null= ''
  3.  
    a= '{"errno":0,"errmsg":null,"unassigned":0,"total":0,"list":null}'
  4.  
    a=eval(a)
  5.  
    print type(a)


發現這時就可以正常轉換了。

 

二、使用json模塊的loads()方法

這是一個大殺器,直接使用如下語句:

 

  1.  
    a=json.loads(a)
  2.  
    print type(a)

完事,轉換正常,python自動把null轉換為了python支持的None。

 

當然,要記得引入json。

 

注意:json字符串中,必須用雙引號,如果定義成下面這樣,是不對的

 

a="{'errno':0,'errmsg':null}"


使用json,loads()時會報錯:

 

ValueError: Expecting property name: line 1 column 1 (char 1)

 https://blog.csdn.net/onlyanyz/article/details/45745045


免責聲明!

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



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