Typeerror: encoders require their input to be uniformly strings or numbers. got [‘int’, ‘str’]

The error “TypeError: encoders require their input to be uniformly strings or numbers” occurs when you try to encode or convert a non-string or non-number object.

In this case, the error message specifies that the input is [‘int’, ‘str’], which means that the encoder function expected only strings or numbers but received a combination of integers and strings.

To address this error, you need to make sure that all the inputs you provide to the encoder function are either strings or numbers, but not a mix of both.

Here’s an example to illustrate the issue:

    import json

    data = {
        "name": "John Doe",
        "age": 30,
        "city": "New York"
    }

    # Trying to encode the data to JSON
    json_data = json.dumps(data)
    # This will raise a TypeError because age is an integer, not a string

    print(json_data)
  

To fix this specific example, you need to ensure that the ‘age’ value is converted to a string before encoding:

    import json

    data = {
        "name": "John Doe",
        "age": 30,
        "city": "New York"
    }

    # Converting the 'age' value to a string before encoding
    data["age"] = str(data["age"])

    # Encoding the data to JSON
    json_data = json.dumps(data)

    print(json_data)
  

In this updated example, the ‘age’ value is converted to a string using the ‘str()’ function before encoding the data to JSON. This ensures that all the values are uniformly either strings or numbers, avoiding the TypeError.

Related Post

Leave a comment