TypeError: Object of type TypeError is not JSON serializable Python

Viewed 2473

So I have JSON request with format like this:

{
"item_ids": [635,10,692,194,9412],
"gender": "male",
"number_results": 5
}

I'm trying to parse array in "item_ids". But I got error message like in the title. This is my code:

resto_id = json.loads['item_ids']
data  = json.dumps(resto_id)

I also tried this:

response = requests.get("http://127.0.0.1:8520/recommend_multi")
users = json.loads(response.text)
data = users['item_ids']

But gave me an error:

TypeError: Object of type JSONDecodeError is not JSON serializable

Edit: Maybe this will help:

@app.route('/recommend_multi', methods=['POST'])
def recommend_multi():

    dct={}
    new_user = 'newusername'
    try:
        e=""
        resto_id = json.loads['item_ids']
        data  = json.dumps(resto_id)
        # response = requests.get("http://127.0.0.1:8520/recommend_multi")
        # users = json.loads(response.text)
        # data = users['item_ids']
        
        gender = request.json['gender']
        resto_rec = float(request.json['number_results'])

        input_dict = {'id_resto': data,
        'gender': [gender, gender, gender, gender, gender], 'username': [new_user, new_user, new_user, new_user, new_user]}
        
        dct = {"items": input_dict}
        dct2 = {"data": dct, "message":"sukses", "success":True}

    except Exception as e:
        dct2 = {"data": dct, "message":e, "success":False}
    

    return jsonify(dct2)

And this is the traceback: enter image description here enter image description here I run it with docker. And for request I'm using Insomnia

2 Answers

The problem is in this snippet:

    except Exception as e:
        dct2 = {"data": dct, "message":e, "success":False}

You are basically trying to JSON serialize the exception e which is not possible. You need to use something that is JSON serializable, like the string representation of the exception, for example by using str(e):

    except Exception as e:
        dct2 = {"data": dct, "message":str(e), "success":False}

First, thanks to @bdbd to keep responding to me. The exception solution helped me to fix my code, but in the end I managed to debug my code then found the solution which is resolve my problems about retrieving array in JSON objects. So instead of this:

resto_id = json.loads['item_ids']
data  = json.dumps(resto_id)

I need to request first.

resto_id = request.json
data  = json.dumps(resto_id)
data2 = json.loads(data)
#Then retrieve the array
data2["item_ids"]
Related