It appears that you're encountering a JSON parsing error when attempting to process the response from the API. This issue could be due to several reasons, such as the response not being valid JSON, encoding issues, or unnecessary manipulation of the response text before parsing.
Here's how you can address this problem:
-
Avoid Manipulating the Response Before Parsing:
Modifying the response text before parsing can lead to further complications. The replacements you're making could corrupt the JSON structure, making it unparsable. It's best to parse the JSON as-is.
-
Use response.json() Instead of response.text:
The requests library provides a convenient method response.json(), which automatically parses the response content as JSON. It's also better at handling encoding issues. If the response isn't valid JSON, it will raise an exception, which you can catch and handle.
-
Check the Actual Response Content:
It's important to inspect the content of the response to ensure it's what you expect. The API might be returning an error message, HTML content, or otherwise malformed JSON.
Here's the revised code with these considerations:
import requests
import json
def LoadFromSite():
session = requests.Session()
session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0'
})
headers = {
'X-LHD-Agent': '{"platform":"web","app":"tvplusonline.ru"}'
}
url = 'http://tvplusonline.ru/api/v4/playlist'
try:
response = session.get(url, headers=headers, timeout=8)
if response.status_code != 200:
print(f"Request failed with status code {response.status_code}")
return
try:
tab = response.json()
except json.JSONDecodeError as e:
print(f"JSON parsing error: {e}")
print("Response content:")
print(response.text)
return
if not tab or 'channels' not in tab:
print("No 'channels' key in the response JSON.")
return
t = []
for channel_info in tab['channels']:
slug = channel_info.get('address')
title = channel_info.get('name_ru')
if slug and title:
channel = {}
channel['name'] = title.strip() # Assuming you want to remove extra spaces
channel['address'] = f"http://example.com/{slug}" # Replace 'http://example.com' with the actual host
if channel_info.get('with_archive'):
day_archive = channel_info.get('day_archive', 0)
channel['RawM3UString'] = f'catchup="append" catchup-days="{day_archive}" catchup-source=""'
channel['logo'] = channel_info.get('image', '')
t.append(channel)
# Assuming ProcessFilterTableLocal is a function you've defined elsewhere
# t = ProcessFilterTableLocal(t)
return t
except requests.RequestException as e:
print(f"Request error: {e}")
return
# Run the function
channels_data = LoadFromSite()
# Print the result if needed
if channels_data:
for channel in channels_data:
print(channel)
Notes:
-
Removed Unnecessary Replacements: The code that was manipulating the answer variable before parsing has been removed. This prevents potential corruption of the JSON data.
-
Used response.json(): This method handles JSON parsing and will automatically raise a json.JSONDecodeError if the content isn't valid JSON.
-
Added Debugging Prints: If there's a JSON parsing error, the code now prints the error and the actual response content. This can help you understand what's wrong with the response.
-
Handled Missing Functions and Variables: Since tvs_clear_double_space, unescape3, ProcessFilterTableLocal, and host were not defined in your code snippet, I've made assumptions or commented them out. You should replace these with your actual implementations or remove them if not necessary.
-
Checked for 'channels' Key: Added a check to ensure the 'channels' key is present in the parsed JSON.
Next Steps:
-
Run the Revised Code: Execute the updated script to see if the JSON parsing error persists.
-
Inspect the Response Content: If the error still occurs, look at the printed response content to see if it contains valid JSON or an error message from the server.
-
Verify API Availability: Ensure that the API endpoint http://tvplusonline.ru/api/v4/playlist is correct and accessible.
-
Check for Additional Requirements: Some APIs require authentication tokens, specific headers, or cookies. Make sure you're providing everything the API needs to return a valid response.
-
Handle Encoding Issues: If the response contains special characters or uses a different encoding, you might need to handle the encoding explicitly.
-
Update Undefined Functions: Make sure all functions and variables used in the code are properly defined.
Example Output Handling:
If after running the code you still encounter issues, please share the printed response content (ensure you redact any sensitive information). This will help further diagnose the problem.