복붙노트

[PYTHON] TypeError : b'1 '은 JSON 직렬 가능하지 않습니다.

PYTHON

TypeError : b'1 '은 JSON 직렬 가능하지 않습니다.

JSON으로 POST 요청을 보내려고합니다.

* 전자 메일 변수의 형식은 "바이트"입니다.

def request_to_SEND(email, index):
    url = "....."
    data = {
        "body": email.decode('utf-8'),
        "query_id": index,
        "debug": 1,
        "client_id": "1",
        "campaign_id": 1,
        "meta": {"content_type": "mime"}
    }
    headers = {'Content-type': 'application/json'}

    try:
        response = requests.post(url, data=json.dumps(data), headers=headers)
    except requests.ConnectionError:
        sys.exit()

    return response

오류가 발생했습니다.

 File "C:\Python34\lib\json\encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'1' is not JSON serializable

내가 잘못하고 있는게 뭐라 구요?

해결법

  1. ==============================

    1.이것은 데이터 딕트 (b'1 ', 구체적으로)에 bytes 객체를 전달하고 있기 때문에 발생하는 것입니다 (특히 인덱스의 값). json.dumps가 작업하기 전에 str 객체로 디코딩해야합니다.

    이것은 데이터 딕트 (b'1 ', 구체적으로)에 bytes 객체를 전달하고 있기 때문에 발생하는 것입니다 (특히 인덱스의 값). json.dumps가 작업하기 전에 str 객체로 디코딩해야합니다.

    data = {
        "body": email.decode('utf-8'),
        "query_id": index.decode('utf-8'),  # decode it here
        "debug": 1,
        "client_id": "1",
        "campaign_id": 1,
        "meta": {"content_type": "mime"}
    }
    
  2. from https://stackoverflow.com/questions/24369666/typeerror-b1-is-not-json-serializable by cc-by-sa and MIT license