JSONDecodeError:期望值:第 1 行第 1 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34579327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:12:39  来源:igfitidea点击:

JSONDecodeError: Expecting value: line 1 column 1

jsonpython-3.x

提问by beeny

I am receiving this error in Python 3.5.1.

我在 Python 3.5.1 中收到此错误。

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

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

Here is my code:

这是我的代码:

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))

image

图片

回答by Dan Lowe

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):

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

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

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

如果您使用诸如 之类的工具获取 URL curl -v,您将看到内容类型为

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

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.

所以它是 JSON,编码为 UTF-8,Python 认为它是一个字节流,而不是一个简单的字符串。为了解析它,您需要先将其转换为字符串。

Change the last line of code to this:

把最后一行代码改成这样:

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

回答by Andy Yuan

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) exceptto check your input

在我的例子中,像 ", :"'{}[] " 这样的字符可能会破坏 JSON 格式,所以使用try json.loads(str) 除了检查您的输入