Python ValueError: 디코딩할 수 있는 JSON 개체가 없습니다.

Salman Mehmood 2023년6월21일
  1. Python에서 JSON 객체 디코딩
  2. JSON 문자열을 Python 객체로 디코딩
  3. Python 객체를 JSON 문자열로 인코딩
Python ValueError: 디코딩할 수 있는 JSON 개체가 없습니다.

이름 오류, Python 개체를 JSON으로 인코딩하는 방법, 인접한 문자열을 Python 개체로 디코딩하는 방법에 대해 설명합니다. 또한 JSON 데이터를 구문 분석하지 못하는 이유도 알아봅니다.

Python에서 JSON 객체 디코딩

json 모듈을 가져와 시작하겠습니다. 이 세션에서는 Python 개체를 인접한 텍스트로 인코딩 및 디코딩할 계획입니다. 따라서 다음 줄로 전환하고 키-값 쌍이 있는 작은 문자열 전체를 저장할 변수를 정의합니다.

이것을 인쇄하면 변수에 정의한 대로 인쇄되는 것을 볼 수 있습니다. 즉, 문자열입니다.

암호:

import json

Sample_json = '{"Employee_Name":"Garry","Employee_Age":29}'
print(Sample_json)
# We can see the type of this Sample_json using the type() function
print(type(Sample_json))

출력:

{"Employee_Name":"Garry","Employee_Age":29}
<class 'str'>

JSON 문자열을 Python 객체로 디코딩

이제 우리는 그것을 파이썬 객체로 디코딩해야 했고, 그것은 정확히 파이썬 사전으로 변환되었습니다. json.loads() 메서드를 사용하여 인접한 문자열을 디코딩하고 동시에 개체 유형도 인쇄합니다.

import json

Sample_obj = json.loads(Sample_json)
print(Sample_obj)
print(type(Sample_obj))

출력:

{'Employee_Name': 'Garry', 'Employee_Age': 29}
<class 'dict'>

Python 객체를 JSON 문자열로 인코딩

이제 json.loads() 메서드를 사용하여 JSON 문자열을 Python 사전 객체로 디코딩할 수 있음을 확인했습니다. Python 개체를 변환하거나 Python 개체를 JSON 문자열로 인코딩하는 또 다른 예를 살펴보겠습니다.

사전이 될 Sample_json2라는 개체를 하나 더 정의해 보겠습니다. 이를 JSON으로 변환하기 위해 json.dumps() 메서드를 사용합니다.

그런 다음 JSON 문자열로 인코딩하려는 개체를 제공합니다. 이제 dumps() 메서드가 생성한 출력 유형을 볼 수 있으며 해당 유형이 str(문자열)임을 알 수 있습니다.

암호:

import json

Sample_json2 = {"Employee_Name": "Garry", "Employee_Age": 29}
print(Sample_json2)
print(type(Sample_json2))
temp = json.dumps(Sample_json2)
print(temp)
print(type(temp))

출력:

{'Employee_Name': 'Garry', 'Employee_Age': 29}
<class 'dict'>
{"Employee_Name": "Garry", "Employee_Age": 29}
<class 'str'>

dumps() 메소드는 Python 객체를 인접한 문자열로 인코딩하고 loads() 메소드는 JSON 문자열을 Python 객체로 디코딩합니다. 이 접근 방식을 따르면 JSON 데이터를 구문 분석할 때 가끔 발생하는 값 오류가 발생하지 않습니다.

Python에서 JSON 데이터를 구문 분석하지 못하는 데는 여러 가지 이유가 있을 수 있습니다. 그 중 하나는 때때로 빈 문자열이나 빈 파일을 디코딩하려고 하거나 JSON 파일의 잘못된 경로를 제공하는 것입니다.

Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn

관련 문장 - Python Error