【问题标题】:Python JSONDecodeError: Expecting value: line 1 column 1Python JSONDecodeError:期望值:第 1 行第 1 列
【发布时间】:2019-08-10 12:59:59
【问题描述】:

我收到一个错误:JSONDecodeError: Expecting value: line 1 column 1 (char 0)。但是不明白为什么。

这是我的代码:

import json
import urllib.request

url = "apiurl"
data = json.loads(url)

# Open the URL as Browser, not as python urllib
page = urllib.request.Request(url,headers={'User-Agent': 'Mozilla/5.0'})
infile = urllib.request.urlopen(page).read()
data = infile.decode('ISO-8859-1')  # Read the content as string decoded with ISO-8859-1

command_obj = {x['command']: x for x in data}

with open('new_command.json', 'w') as f:
    json.dump(command_obj, f, indent=2)

有了这个功能,我只是想从一个 api 中获取数据并修改它的格式。感谢您的帮助

【问题讨论】:

  • 您的 url 是 JSON 对象的文本表示吗?
  • 这是一个 json 对象是的!这是网址:api.sheety.co/be29a67e-80b2-4f73-ace9-9a0a2f40f4a6
  • URL 本身 ("https://api.sheety.co/be29a67e-80b2-4f73-ace9-9a0a2f40f4a6") 是 JSON 对象吗? json.loads(url) 将尝试将这个字符串解析为 JSON 对象。

标签: python json


【解决方案1】:

您正在尝试将 URL 本身(而不是其内容)读取为 JSON:

data = json.loads(url)

...相反,您希望将 API 返回的 内容 读取为 JSON:

# Open the URL as Browser, not as python urllib
page = urllib.request.Request(url,headers={'User-Agent': 'Mozilla/5.0'})
infile = urllib.request.urlopen(page).read()
data = infile.decode('ISO-8859-1')

# avoid re-using `data` variable name
json_data = json.loads(data)

但是,请注意 JSON 应始终以 UTF-8 形式返回,而不是 ISO-8859-1 / latin-1。

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 2019-07-04
    • 2020-04-18
    • 2013-05-10
    • 2019-02-25
    • 2020-02-03
    • 2021-09-30
    相关资源
    最近更新 更多