There are a couple of ways to resolve the issue of "Extra data" in JSONDecodeError with Python:
json.loads()
method to load the data as a list of individual JSON objects, and then iterate through the list to process each object separately.import json
data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]{"country": "USA"}'
objects = data.split('}{')
for i in range(0, len(objects)):
if i == 0:
objects[i] += '}'
elif i == len(objects) - 1:
objects[i] = '{' + objects[i]
else:
objects[i] = '{' + objects[i] + '}'
for obj in objects:
try:
json_obj = json.loads(obj)
print(json_obj)
except json.JSONDecodeError as e:
print(f"Error: {e}")
json.JSONDecoder()
class to decode the JSON data and pass the object_hook
argument to handle the extra data.import json
class JsonDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
super().__init__(object_hook=self.dict_to_object, *args, **kwargs)
def dict_to_object(self, d):
return d
decoder = JsonDecoder()
data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]{"country": "USA"}'
try:
json_obj = decoder.decode(data)
print(json_obj)
except json.JSONDecodeError as e:
print(f"Error: {e}")
Both of these methods should allow you to process the JSON data even when there is extra data present.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-02 17:51:11 +0000
Seen: 9 times
Last updated: Jun 02 '23
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?