2016-08-12 6 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) が何らかの理由でそれを解析することはできませんし、私は次の例外を得ることです:私はそれがデータ型をbecuaseが、その奇妙なことをやって思った

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

を。 私は型(データ)を求めていますが、str型を取得していますが、データを出力するときにはByte型を取得します。

コードのフル出力:

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

あなたが変換していますあなたはstr()対象とすることを余儀なくさ

data = str(row[1]) 

が、bytesオブジェクトのための:文字列にbytes値ここで間違った方法bytesオブジェクトには__str__メソッドがないため、__repr__しかないので、にはbの接頭辞と引用符が含まれるため、デバッグ表現が得られます。

デコード文字列に変換するなし行

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

は私と同じ問題を解決しました。

関連する問題