Python ValueError:无法解码 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26808814/
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-08-19 01:02:35  来源:igfitidea点击:

Python ValueError: No JSON object could be decoded

pythonjson

提问by Nikolas Daroit

I'm trying to read a json and get its values. I have a folder with the JSON's archives, and I need to open all archives and get the values from them.

我正在尝试读取 json 并获取其值。我有一个包含 JSON 档案的文件夹,我需要打开所有档案并从中获取值。

This is the code:

这是代码:

# -*- encoding: utf-8 -*-
from pprint import pprint
import json
import os 
def start():
    for dirname, dirnames, filenames in os.walk('test'):
        for filename in filenames:
            json_file = open(os.path.join(dirname, filename)).read()
            # json_file = unicode(json_file, 'utf-8')
            json_data = json.loads(json_file)
           pprint(json_data)
            for key, value in json_data.items():
                print "KEY : ", key
                print "VALUE: ", value
                start()

This is one of the JSON's

这是 JSON 之一

{ "test" : "Search User 1",
   "url"  : "http://127.0.0.1:8000/api/v1/user/1/?format=json",
   "status_code" : 200,
   "method" : "get"
}

But when I run it, i get this:

但是当我运行它时,我得到了这个:

ValueError: No JSON object could be decoded

What the hell is wrong? Yesterday it was working exactly as it is now, or am I crazy

这到底是怎么回事?昨天它完全像现在一样工作,或者我疯了

I tried this way:

我试过这种方式:

from pprint import pprint
import json
import os
for dirname, dirnames, filenames in os.walk('test'):
    for filename in filenames:
        json_file_contents = open(os.path.join(dirname, filename)).read()
        try:
            json_data = json.loads(json_file_contents)
        except ValueError, e:
            print e
            print "ERROR"

I cant see any error '-'

我看不到任何错误“-”

for filename in filenames:
        with open(os.path.join(dirname,filename)) as fd:
            json_data = fd.read()
            print json_data

This way I can see what the json files contain, but I can't use for example access by the key, like json_data['url']

这样我可以看到 json 文件包含什么,但我不能使用例如通过密钥访问,比如 json_data['url']

采纳答案by Curtis Mattoon

It's possible the .read()method is moving the cursor to the end of the file. Try:

.read()方法可能将光标移动到文件末尾。尝试:

for filename in filenames:
    with open(os.path.join(dirname,filename)) as fd:
        json_data = json.load(fd)

and see where that gets you.

看看这让你在哪里。

This, of course, assumes you have valid JSON, as your example demonstrates. (Look out for trailing commas)

当然,这假设您拥有有效的 JSON,如您的示例所示。(注意尾随逗号)

回答by waltersantosf

I had the same problem today. Trying to understand the cause, I found this issue related to jsonmodule:

我今天遇到了同样的问题。试图了解原因,我发现这个问题与json模块有关:

http://bugs.python.org/issue18958

http://bugs.python.org/issue18958

Check if the file is UTF8 encoded and if it is the case, then use codecsmodule to open and read it or just skip the BOM (byte order mark).

检查文件是否为 UTF8 编码,如果是,则使用codecs模块打开并读取它或跳过 BOM(字节顺序标记)。

回答by Ella Cohen

For me it was an encoding problem, you can try using Notepad++to edit your .json file and change the Encoding to UTF-8 without BOM. Another thing you could check is if your json script is valid

对我来说,这是一个编码问题,您可以尝试使用Notepad++编辑您的 .json 文件并将编码更改为 UTF-8 而不使用 BOM。您可以检查的另一件事是您的 json 脚本是否有效

回答by Jerry K.

The reply suggesting that .read() was moving the cursor led to a resolution of my version of the problem. I changed

暗示 .read() 正在移动光标的回复导致我的问题版本得到解决。我变了

print response.read()
...
json_data = json.loads(response.read())

to

responseStr = response.read()
print responseStr
...
json_data = json.loads(responseStr)

回答by user2092402

I resolved this error by Converting the json file to UTF-8 with no BOM. Below is a python snippet and urlfor conversion

我通过将 json 文件转换为没有 BOM 的 UTF-8 解决了这个错误。以下是用于转换的 python 代码段和url

myFile=open(cases2.json, 'r')
myObject=myFile.read()
u = myObject.decode('utf-8-sig')
myObject = u.encode('utf-8')
myFile.encoding
myFile.close()
myData=json.loads(myObject,'utf-8')

回答by sam ruben

Try using this in your ajax/$http with JSON data

尝试在带有 JSON 数据的 ajax/$http 中使用它

contentType: "application/json; charset=utf-8"

内容类型:“应用程序/json;字符集=utf-8”