JSONDecodeError:预期值:第1行第1列 [英] JSONDecodeError: Expecting value: line 1 column 1

查看:141
本文介绍了JSONDecodeError:预期值:第1行第1列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python 3.5.1.中收到此错误.

I am receiving this error in Python 3.5.1.

json.decoder.JSONDecodeError:预期值:第1行第1列(字符0)

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是我的代码:

import json
import urllib.request

connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json')

js = connection.read()

print(js)

info = json.loads(str(js))

推荐答案

如果您查看从print()以及在Traceback中收到的输出,您将看到返回的值不是字符串,而是一个字节对象(以b为前缀):

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

如果您使用curl -v之类的工具提取网址,则会看到内容类型为

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

因此它是JSON,编码为UTF-8,Python正在考虑将其作为字节流,而不是简单的字符串.为了对此进行解析,您需要先将其转换为字符串.

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

将最后一行代码更改为此:

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

这篇关于JSONDecodeError:预期值:第1行第1列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆