2016-08-12 36 views
0

我想解析一個JSON,但它不起作用。 我刪除了我的代碼中的try和except,以便您可以看到Error Massege。Python 3 json.loads - json.decoder錯誤

import sqlite3 
import json 
import codecs 

conn = sqlite3.connect('geodata.sqlite') 
cur = conn.cursor() 

cur.execute('SELECT * FROM Locations') 
fhand = codecs.open('where.js','w', "utf-8") 
fhand.write("myData = [\n") 
count = 0 
for row in cur : 
    data = str(row[1]) 
    print (data) 
    print (type(data)) 
    #try: 
    js = json.loads(data) 
    #except: continue 

    if not('status' in js and js['status'] == 'OK') : continue 

    lat = js["results"][0]["geometry"]["location"]["lat"] 
    lng = js["results"][0]["geometry"]["location"]["lng"] 
    if lat == 0 or lng == 0 : continue 
    where = js['results'][0]['formatted_address'] 
    where = where.replace("'","") 
    try : 
     print (where, lat, lng) 

     count = count + 1 
     if count > 1 : fhand.write(",\n") 
     output = "["+str(lat)+","+str(lng)+", '"+where+"']" 
     fhand.write(output) 
    except: 
     continue 

fhand.write("\n];\n") 
cur.close() 
fhand.close() 
print (count, "records written to where.js") 
print ("Open where.html to view the data in a browser") 

我的問題是 js = json.loads(data) 無法解析它由於某種原因,我得到以下異常:

"raise JSONDecodeError("Expecting value", s, err.value) from None 
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 

我認爲這監守的數據類型,但它做了奇怪的事情。 我要求類型(數據),我得到str類型,但是當我打印數據時,我得到字節類型。

的代碼全部輸出:

Traceback (most recent call last): 
    File "C:/Users/user/Desktop/Courses Online/Coursera/Using Databases with Python/geodata/geodump.py", line 17, in <module> 
    js = json.loads(data) 
    File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads 
    return _default_decoder.decode(s) 
    File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode 
    raise JSONDecodeError("Expecting value", s, err.value) from None 
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 
b'{\n "results" : [\n  {\n   "address_components" : [\n   {\n ...... long json line...... 
<class 'str'> 

我也嘗試使用數據解碼( 「UTF-8」),但我發現了以下錯誤:'str' object has no attribute 'decode'

回答

0

要轉換一個bytes值的字符串錯誤的方式在這裏:

data = str(row[1]) 

你強迫它是一個str()對象,但對於bytes對象那會包含b前綴和引號,因爲bytes對象沒有__str__方法,只有__repr__這樣你纔會得到一個調試表示。

解碼行沒有轉換爲字符串:

data = row[1].decode('utf8') 

你真的不應該手工工藝在你的代碼JSON/JavaScript的輸出要麼。只需使用json.dumps();如果你必須採用每排流,你仍然可以使用json.dump()創建每個列表條目:

import sqlite3 
import json 

conn = sqlite3.connect('geodata.sqlite') 
cur = conn.cursor() 
cur.execute('SELECT * FROM Locations') 

with open('where.js', 'w', encoding="utf-8") as fhand: 
    fhand.write("myData = [\n") 
    for count, row in enumerate(row): 
     try: 
      js = json.loads(row[1].decode('utf8')) 
     except json.JSONDecodeError: 
      print('Could not decode a row: ', row[1]) 
      continue 

     if js.get('status') != 'OK': 
      continue 

     lat = js["results"][0]["geometry"]["location"]["lat"] 
     lng = js["results"][0]["geometry"]["location"]["lng"] 
     if not (lat and lng): 
      continue 

     where = js['results'][0]['formatted_address'] 
     where = where.replace("'", "") 
     print (where, lat, lng) 

     if count: fhand.write(",\n") 
     json.dump([lat, lng, where], fhand) 

fhand.write("\n];\n") 

此使用純open()(在Python 3中,從來就沒有必要使用codecs.open()),使用文件作爲上下文管理器,並添加enumerate()以跟蹤是否已處理第一行。

0
js = json.loads(data.decode('utf8')) 

對我解決了同樣的問題。