Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a couple of ways to resolve the issue of "Extra data" in JSONDecodeError with Python:

  1. Use the 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}")
  1. Use the 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.