You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供打开指定JSON文件的代码,解决JSONDecodeError问题

Fixing JSONDecodeError for Madrid's Public Parking Data API

Hey there! That JSONDecodeError: Expecting value: line 1 column 1 (char 0) usually pops up when the server isn't returning valid JSON. Most often, this happens because the site is blocking your request (treating it as an automated bot) or sending back an error page instead of the data. Let's fix this with a few adjustments to your request.

Why This Happens

  • Many public data portals block requests without a proper User-Agent header (they look like bots).
  • The server might be returning a redirect, error page, or empty response instead of JSON.

Working Code with Error Handling

Here's a robust script that adds browser-like headers and includes error handling to debug issues:

import requests

# Target URL for Madrid's public parking data
url = "https://datos.madrid.es/egob/catalogo/202625-0-aparcamientos-publicos.json"

# Mimic a real browser request to avoid being blocked
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    "Accept": "application/json, text/javascript, */*; q=0.01"
}

try:
    # Send the request with headers
    response = requests.get(url, headers=headers)
    
    # Raise an error if the request failed (e.g., 404, 500)
    response.raise_for_status()
    
    # Parse the JSON response
    parking_data = response.json()
    
    # Verify success by printing top-level data
    print("✅ Successfully fetched and parsed data!")
    print(f"Top-level keys in the JSON: {list(parking_data.keys())}")

except requests.exceptions.HTTPError as http_error:
    print(f"❌ HTTP Error occurred: {http_error}")
    # Print first 500 characters of the response to debug
    print("Response preview (non-JSON content):")
    print(response.text[:500])
except ValueError as json_error:
    print(f"❌ JSON Decode Error: {json_error}")
    print("Response that caused the error:")
    print(response.text[:500])
except Exception as general_error:
    print(f"❌ Unexpected error: {general_error}")

Key Fixes Explained

  • User-Agent Header: Tells the server we're a real browser, not an automated script. This is the most common fix for this error.
  • Accept Header: Specifies we prefer JSON, which helps the server return the correct content type.
  • Error Handling: Catches HTTP errors and JSON decoding issues, plus shows a preview of the response to debug what's going wrong.

If You Still Have Issues

If the error persists, check the response.text output. It might show:

  • A login prompt or captcha (unlikely for this public data set, but possible)
  • A redirect to a different URL
  • An HTML error page (e.g., 403 Forbidden)

You can adjust the headers further or handle redirects by adding allow_redirects=True to the requests.get() call (it's enabled by default, but sometimes explicit helps).

内容的提问来源于stack exchange,提问作者Marta Bescansa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:02:34