简体   繁体   English

如何解决序列化 JSON 的这个问题?

[英]How can I fix this problem serializing JSON?

I want to post input data with python to a JSON document database.我想将带有 python 的输入数据发布到 JSON 文档数据库。 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:ayoub_semsar@yahoo.com
>>> 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))

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]}

You are trying to insert a string instead of object (or vice versa).您正在尝试插入字符串而不是 object(反之亦然)。

For example;例如;

This is a valid JSON:这是一个有效的 JSON:

{"full_name": "ayoub"}

Or this is another valid JSON:或者这是另一个有效的 JSON:

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

However, this is the JSON that returns from your code (let's include just the first column):但是,这是从您的代码返回的 JSON(让我们只包括第一列):

{"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:您需要从字典中删除大括号,或者您应该将它们转换为 JSON 列表,其中可以包含多个字符串:

  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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM