Python 3 json.loads-json.decoder错误
我正在尝试解析json,但它不起作用。 我在代码中删除了try和except,以便您可以看到错误MassegePython 3 json.loads-json.decoder错误,python,python-3.x,Python,Python 3.x,我正在尝试解析json,但它不起作用。 我在代码中删除了try和except,以便您可以看到错误Massege 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.
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.load(数据)
由于某种原因无法分析它,我遇到以下异常:
"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'>
回溯(最近一次呼叫最后一次):
文件“C:/Users/user/Desktop/Courses Online/Coursera/Using Databases with Python/geodata/geodump.py”,第17行,在
js=json.load(数据)
文件“C:\Users\user\AppData\Local\Programs\Python35-32\lib\json\\ uu_init\u_.py”,第319行,加载
返回\u默认\u解码器。解码
文件“C:\Users\user\AppData\Local\Programs\Python35-32\lib\json\decoder.py”,第339行,在decode中
obj,end=self.raw\u decode(s,idx=\u w(s,0.end())
文件“C:\Users\user\AppData\Local\Programs\Python35-32\lib\json\decoder.py”,第357行,原始解码
从None引发JSONDecodeError(“预期值”,s,err.value)
json.decoder.JSONDecodeError:预期值:第1行第1列(字符0)
b'{\n“结果”:[\n{\n“地址\u组件”:[\n{\n……长json行。。。。。。
我还尝试对数据使用decode(“utf-8”),但我得到了以下错误:
'str'对象没有属性“decode”
您在这里以错误的方式将字节
值转换为字符串:
data = str(row[1])
您强制它是一个str()
对象,但是对于字节
对象,它将包含b
前缀和引号,因为字节
对象没有\u str\u
方法,只有\u repr\u
才能获得调试表示
解码行而不转换为字符串:
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()
中以跟踪是否处理了第一行
js = json.loads(data.decode('utf8'))
为我解决了同样的问题