在學習python語言中用json庫解析網絡數據時,我遇到了兩個編譯錯誤:json.decoder.jsondecodeerror: expecting property name enclosed in double quotes:和json.decoder.jsondecodeerror: expecting value:。費了一些時間才找到原因,在此記錄總結,希望能對學習python的同學有所幫助。
我運行的程序初始如下:
1
2
3
4
5
6
7
8
9
10
|
import json data = ''' { 'name' : 'a', 'phone': { 'type' : 'intl', 'number' : +1 23456 }, 'email' : {'hide' : 'yes'} }''' info = json.loads(data) print ( "name:" ,info[ "name" ]) print ( "emailattri:" ,info[ "email" ][ "hide" ]) |
運行后報錯,顯示錯誤為json.decoder.jsondecodeerror: expecting property name enclosed in double quotes:,原來數據格式里string類型的數據要用雙引號'' '',而不能用單引號' '。
將里面的單引號一一改過來之后,編譯器仍然報錯:json.decoder.jsondecodeerror: expecting value:。我以為是代碼格式(縮進)的問題,反復修改后還是報錯,這讓我百思不得其解,在網上搜索了這一錯誤的解決方案,也沒有找到合適的答案。最后,與老師的源代碼逐一仔細比對,發現問題竟然出在"number"這個元素這里,我當時把它的值當作數字,其實在這里+1 23456是string類型,因此需要加上雙引號。修改后程序如下,正確運行。
1
2
3
4
5
6
7
8
9
10
|
import json data = ''' { "name" : "a", "phone": { "type" : "intl", "number" : "+1 23456" }, "email" : {"hide" : "yes"} }''' info = json.loads(data) print ( "name:" ,info[ "name" ]) print ( "emailattri:" ,info[ "email" ][ "hide" ]) |
這個問題還有另一種解決方式,就是將+1 23456改寫成123456,int類型,這樣就不需要加雙引號。
我在網上搜索該問題時,發現有很多人也遇到了json.decoder.jsondecodeerror: expecting value:這一錯誤,從我解決的過程中,我認為原因主要是數據的格式不正確。因此,如果是從網上爬取的數據,需要先檢查一下數據格式設置是否符合json的要求,這樣程序編譯才能順利通過。
更多趣事,python知識,可以關注小編的微信公眾號【碼農那點事兒】。
總結
以上所述是小編給大家介紹的python中報錯"json.decoder.jsondecodeerror: expecting value:"的解決 ,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
原文鏈接:https://www.cnblogs.com/codestack123/archive/2019/04/29/10789640.html