Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 바이트 배열을 JSON 형식으로 어떻게 변환할 수 있습니까?


문자열을 생성하려면 바이트열 객체를 디코딩해야 합니다. 이것은 디코딩하려는 인코딩을 수락할 문자열 클래스의 디코딩 기능을 사용하여 수행할 수 있습니다.

my_str = b"Hello" # b means its a byte string
new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding
print(new_str)

출력

이것은 출력을 제공합니다

Hello

바이트열이 문자열이면 JSON.dumps 메서드를 사용하여 문자열 개체를 JSON으로 변환할 수 있습니다.

my_str = b'{"foo": 42}' # b means its a byte string
new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding

import json
d = json.dumps(my_str)
print(d)

출력

이것은 출력을 제공합니다 -

"{\"foo\": 42}"