首页 > 解决方案 > 频繁的 json 解码器错误 - decoder.py 第 357 行,在 raw_decode

问题描述

我不懂一点 python,下面的脚本是 6 小时谷歌研究的输出。我的任务很简单。想要创建一个包含从 OMDB 中提取的电影信息的文本文件。我将所有电影名称转储到一个文本文件中并运行以下脚本。每次我运行以下脚本时,我只得到 15-20 部电影信息,但之后我得到解码器错误。当我通过删除我已经获得信息的电影名称重新运行时,我再次获得 10-15 电影信息!我不是 Python 方面的专家,但下面的一切看起来都很好,所以不知道我为什么会得到这个。

import json
import requests
import sys
import time

if(len(sys.argv) != 2):
    print("Please provide the movie file name as input arg. Ex " + sys.argv[0] + " movie_names.txt")
    print("Please note that in movie file each movie name should be on a new line")
else:
    with open(sys.argv[1]) as f:
        for line in f:
            json_obj_movie_detail = requests.get ("http://www.omdbapi.com/?t=\"" + line.rstrip('\n') + "\"&apikey=$$$$$$$")
            j = json.loads( json_obj_movie_detail.content )
            if(j.get('Title')):
                print (j['Title']+ ";" , end='', flush=True)
            else:
                print (line.rstrip('\n') + ";" + "Could not find this movie!", end='', flush=True)

            if(j.get('Genre')):
                print (j['Genre']+ ";" , end='', flush=True)
            else:
                print ("null" + ";", end='', flush=True)

            if(j.get('Plot')):
                print (j['Plot']+ ";" , end='', flush=True)
            else:
                print ("null" + ";" , end='', flush=True)

            counter = 0

            if(j.get('Title')):
                for each_rating_source in j['Ratings']:
                    print (j['Ratings'][counter]['Source'] + ";", end='', flush=True)
                    print (j['Ratings'][counter]['Value'] + ";", end='', flush=True)
                    counter = counter + 1
            else:
                print ("null", end='', flush=True)

            print(" ")

    f.close()

非常感谢 Python / Json 专家的帮助。

/********* 错误 *****/

Traceback (most recent call last):
  File "C:\Users\peacedove\movie_detail.py", line 13, in <module>
    j = json.loads( json_obj_movie_detail.content )
  File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\peacedove\AppData\Local\Programs\Python\Python36\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)

标签: pythonjson

解决方案


推荐阅读