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

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

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

pythonjson

提问by JTH

I am trying to import a file which was saved using json.dumpsand contains tweet coordinates:

我正在尝试导入一个使用保存json.dumps并包含推文坐标的文件:

{
    "type": "Point", 
    "coordinates": [
        -4.62352292, 
        55.44787441
    ]
}

My code is:

我的代码是:

>>> import json
>>> data = json.loads('/Users/JoshuaHawley/clean1.txt')  

But each time I get the error:

但是每次我收到错误时:

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

I want to end up extracting all the coordinates and saving them separately to a different file so they can then be mapped, but this seemingly simple problem is stopping me from doing so. I have looked at answers to similar errors but don't seem to be able to apply it to this. Any help would be appreciated as I am relatively new to python.

我想最终提取所有坐标并将它们分别保存到不同的文件中,以便可以映射它们,但是这个看似简单的问题阻止了我这样做。我查看了类似错误的答案,但似乎无法将其应用于此。任何帮助将不胜感激,因为我对 python 比较陌生。

采纳答案by Martijn Pieters

json.loads()takes a JSON encoded string, not a filename. You want to use json.load()(no s) instead and pass in an open file object:

json.loads()采用JSON 编码的 string,而不是文件名。您想改用json.load()(no s) 并传入一个打开的文件对象:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open()command produces a file object that json.load()can then read from, to produce the decoded Python object for you. The withstatement ensures that the file is closed again when done.

open()命令生成一个文件对象,json.load()然后可以从中读取,为您生成解码的 Python 对象。该with语句确保文件在完成后再次关闭。

The alternative is to read the data yourself and then pass it into json.loads().

另一种方法是自己读取数据,然后将其传递到json.loads().

回答by Sergey_M

I had similar error: "Expecting value: line 1 column 1 (char 0)"

我有类似的错误:“期望值:第 1 行第 1 列(字符 0)”

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

它帮助我添加“myfile.seek(0)”,将指针移动到 0 字符

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)