파이썬 | 문자열을 json 객체로 변환하는 방법
이 기사에서는 Python에서 문자열을 JSON으로 변환하는 다양한 방법을 살펴보겠습니다. 이 프로세스를 직렬화라고 합니다. JSON 모듈은 Python 객체를 인코딩(직렬화)하는 기능을 제공합니다. JSON 문자열 및 JSON 문자열을 디코딩(역직렬화)합니다. 파이썬 객체 .
- JSON 인코딩(직렬화) : Python 객체가 있고 이를 JSON 문자열로 변환하려는 경우 다음을 사용할 수 있습니다. json.dumps() 기능. Python 개체를 입력으로 사용하고 JSON 문자열을 반환합니다.
- JSON 디코딩(역직렬화) : JSON 문자열이 있고 이를 Python 객체로 변환하려는 경우 다음을 사용할 수 있습니다. json.로드() 기능. JSON 문자열을 입력으로 사용하고 Python 객체를 반환합니다.
Python에서 문자열을 JSON 개체로 변환
다음은 Python 문자열을 JSON 개체로 변환하는 방법입니다.
- 사용 json.로드() 방법
- eval() 메소드 사용
- ast.literal_eval() 메소드 사용
Python에서 json.loads() 메서드를 사용하여 문자열을 JSON으로 변환
이 예에서는 다음을 사용하여 사전을 JSON 개체로 변환합니다. json.dump() 기능. 그런 다음 JSON 객체의 문자열 표현을 다음을 사용하여 사전으로 변환합니다. json.로드() 방법.
파이썬3
import> json> # initialising json object> ini_string> => {> 'nikhil'> :> 1> ,> 'akash'> :> 5> ,> > 'manjeet'> :> 10> ,> 'akshat'> :> 15> }> # printing initial json> ini_string> => json.dumps(ini_string)> print> (> 'initial 1st dictionary'> , ini_string)> print> (> 'type of ini_object'> ,> type> (ini_string))> # converting string to json> final_dictionary> => json.loads(ini_string)> # printing final result> print> (> 'final dictionary'> ,> str> (final_dictionary))> print> (> 'type of final_dictionary'> ,> type> (final_dictionary))> |
산출:
initial 1st dictionary {'manjeet': 10, 'nikhil': 1, 'akshat': 15, 'akash': 5} type of ini_object final dictionary {'nikhil': 1, 'manjeet': 10, 'akshat': 15, 'akash': 5} type of final_dictionary Python에서 eval() 메서드를 사용하여 문자열을 JSON으로 변환
Python의 eval() 함수는 입력된 표현식을 Python 표현식으로 평가하고 프로그램 내에서 Python 표현식(코드)을 실행합니다.
예
이 예에서는 Python을 변환하고 있습니다. 끈 다음을 사용하여 사전에 표현 평가() 메서드 .
파이썬3
# initialising json object string> ini_string> => '''{'nikhil': 1, 'akash' : 5,> > 'manjeet' : 10, 'akshat' : 15}'''> # printing initial json> print> (> 'initial 1st dictionary'> , ini_string)> print> (> 'type of ini_object'> ,> type> (ini_string))> # converting string to json> final_dictionary> => eval> (ini_string)> # printing final result> print> (> 'final dictionary'> ,> str> (final_dictionary))> print> (> 'type of final_dictionary'> ,> type> (final_dictionary))> |
산출:
initial 1st dictionary {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15} type of ini_object final dictionary {'nikhil': 1, 'manjeet': 10, 'akash': 5, 'akshat': 15} type of final_dictionary ast.literal_eval() 메서드를 사용하여 문자열을 JSON으로 변환
ast.literal_eval() 메서드는 Python의 ast(추상 구문 트리) 모듈의 일부입니다. 이 함수는 리터럴로 구성된 문자열인 표현식 노드를 평가하고 이를 Python 사전 객체로 변환합니다.
예
여기서는 이전 모듈의 ast.literal_eval() 메서드를 사용하여 사전의 문자열 표현을 Python으로 변환합니다. 사전 . ast.literal_eval 함수는 문자열을 구문 분석하고 동일한 속성과 값을 가진 Python 사전 객체를 생성합니다. 결과 사전 객체는 dict 유형을 갖습니다. 그런 다음 표준 사전 액세스 표기법(예: dict_obj[name])을 사용하여 사전 개체의 속성에 액세스할 수 있습니다.
파이썬3
import> ast> # initialize the string to be converted> string> => '{'name': 'John', 'age': 30, 'city': 'New York'}'> # use the ast.literal_eval function to parse the string and create a dictionary object> dict_obj> => ast.literal_eval(string)> # printing final result> print> (> 'Initial string dictionary: '> ,string)> print> (> 'Final dictionary: '> ,dict_obj)> print> (> type> (dict_obj))> |
산출:
Initial string dictionary: {'name': 'John', 'age': 30, 'city': 'New York'} Final dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}