Ask Your Question
1

How to resolve the issue of "Extra data" in JSONDecodeError with Python?

asked 2023-06-02 17:51:11 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-02 18:19:01 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-06-02 17:51:11 +0000

Seen: 9 times

Last updated: Jun 02 '23