본문 바로가기
프로그래밍

[JSON / Python]json.decoder.JSONDecodeError: Expecting value: 에러 -Solved[해결됨]

by Mr.noobiest 2023. 12. 5.

 

 

문제 발생

 

셀레니움이나, Flask를 쓰다보면 다음과  비슷한 구문을 사용할때가 있다.

import requests
import json

url="https://www.naver.com"

headers = {'Content-type': 'application/json'}

response = requests.post(url, headers=headers, data=json.dumps(data))

print(response.json())

 

그러면 아마 아래와 같이 JSONDecodeError Error가 발생할것이다.

 


 

이유

requests.get으로 가져온 데이터의 형태가 json()형태가 아니여서 이다.

JSON데이터는 아래와 같은 형태여야 합니다.{[]}

dummy_data = {
    "name": "John Doe",
    "age": 30,
    "email": "johndoe@example.com",
    "address": {
        "street": "123 Street",
        "city": "New York"
    },
    "phone_numbers": ["123-456-7890", "+1 (555) 123-4567"],
    "friends": [
        {"name":"Jane Smith", 
        	"age" : 28, 
        	"email" : 'janesmith@example.com',
           	"address":{
            	"street":"456 Avenue",
               	"city":"San Francisco"
              }
          },
          {"name":"Mike Johnson", 
          	 	"age" : 32, 
          	 	"email" : 'mikejohnson@example.com',
              	  	"address":{
                  	   			'street':"789 Road",
                      		 'city':"Chicago"
                      }
                  }
      ]
}

이외 이미지/영상/파일과 같은 경우는 json이 아니므로, url이나 별도로 처리하는 코드가 필요하다.

 

 


 

해결


1) Json형태의 데이터가 어디있는지를 먼저 찾아야 한다.

import requests
import json


url="https://www.naver.com"

headers = {'Content-type': 'application/json'}

response = requests.post(url, headers=headers)

print(response.text)

 

 


 

 

2) 그 후 BeautifulSoup와 json을 사용해서 추출 + 추출한 string을 json으로 변경 하면 된다.


#기존코드#

import requests
import json
from bs4 import BeautifulSoup as bs

url="https://www.naver.com"

headers = {'Content-type': 'application/json'}

response = requests.post(url, headers=headers)


######################################################################

#추가한 코드#
soup=bs(response.text,'html.parser')

#아무거나 고른것이다#
get1=soup.find('script',{'id':'ad-timeboard-response'})

#추출한 json형태의 String을 json으로 변환
get_json_data=json.loads(get1.text)

 

 

 

끝!

728x90
반응형