Home > other >  How can I fix this problem serializing JSON?
How can I fix this problem serializing JSON?

Time:08-05

I want to post input data with python to a JSON document database. But this error appears. I think it's a problem of serializing but don't think how to fix it:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\33769\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\33769\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\33769\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\33769\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> res  = requests.post(url, headers=headers, data=data)
>>> print(res.text)
{"error":"bad_request","reason":"invalid UTF-8 JSON"}

Here is the code I used:

>>> import requests
>>> import json
>>> url = 'http://admin:pass@localhost:5984/db_reviewin'
>>> data = {'key':'value'}
>>> headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
>>> a = input("ton_nom:")
ton_nom:ayoub
>>> b = input("ton_age")
ton_age16
>>> c = input("gender:")
gender:M
>>> e_mail = input("ton e_mail:")
ton e_mail:[email protected]
>>> d  = input("country:")
country:france
>>> data = {"full_name":{a}, "age":{b}, "gender":{c}, "e_mail":{e_mail}, "country":{d}}
>>> res  = requests.post(url, headers=headers, data=json.dumps(data))

CodePudding user response:

You can't use a set, use a list and make it like this

data = {"full_name":[a], "age":[b], "gender":[c], "e_mail":[e_mail], "country":[d]}

CodePudding user response:

You are trying to insert a string instead of object (or vice versa).

For example;

This is a valid JSON:

{"full_name": "ayoub"}

Or this is another valid JSON:

{"full_name": {"name": "ayoub"}}

However, this is the JSON that returns from your code (let's include just the first column):

{"full_name": {"ayoub"}}

You need to remove curly brackets from inside your dictionary or you should convert them to a JSON list which can contain multiple string inside it:

  1. data = {"full_name": a, "age": b, "gender": c, "e_mail": e_mail, "country": d}
  2. data = {"full_name":[a], "age":[b], "gender":[c], "e_mail":[e_mail], "country":[d]}
  • Related