Python/2.7 information

json.loads 에러시 위치 찾는 방법 꿀팁

qkqhxla1 2019. 12. 2. 14:06

https://stackoverflow.com/questions/19519409/how-to-get-error-location-from-json-loads-in-python


의 내용을 가져옴. 


정규식으로 소스 코드 안의 api의 결과값으로 보이는 json을 파싱하는 프로그램을 만들었다고 가정해보자.


api의 결과값을 잘 가져온것 같은데 json.loads로 파싱해보면 에러가 나는 경우가 많다.


예로..

import json

s = r'[{"prodNo":374834551334,"prodNm":"나주곰탕 600g x 8인분","saleStatus":"A","salePrice":12500,"discountYn":"N","discountPrice":0,"optUseYn":"N","optTextList":[],"labelNoList":null,"mainImg":{"thumb":{"imgUrl":"","imgWidth":70,"imgHeight":70},"wide":{"imgUrl":"","imgWidth":580,"imgHeight":320},"largeImg":{"imgUrl":"","imgWidth":368,"imgHeight":368},"mediumImg":{"imgUrl":"","imgWidth":266,"imgHeight":266}},"mainYn":"Y","couponNm":null,"couponPrice":null,"couponPriceDispYn":"N"},{"prodNo":275632342448,"prodNm":"시원한 \\"갈비탕 600g x 4팩 8인분\\" 감칠맛","saleStatus":"A","salePrice":13900,"discountYn":"N","discountPrice":0,"optUseYn":"N","optTextList":[],"labelNoList":null,"mainImg":{"thumb":{"imgUrl":"","imgWidth":70,"imgHeight":70},"wide":{"imgUrl":"","imgWidth":580,"imgHeight":320},"largeImg":{"imgUrl":"","imgWidth":368,"imgHeight":368},"mediumImg":{"imgUrl":"","imgWidth":266,"imgHeight":266}},"mainYn":"N","couponNm":null,"couponPrice":null}]'
data = json.loads(s)

실제 사이트의 api를 가져왔다.(어떤 사이트인지 유추 가능한 정보는 지움) 


위의 코드가 왜 에러가 나는지 분석하기는 힘들다.


ValueError: Expecting , delimiter: line 1 column 532 (char 531)


라고 나오는데 컬럼 1의 532번째 문자가 문제라는데 저기서 +-5정도의 인덱스의 문제의 문자가 있을것이다.


저 대략적인 위치의 스트링을 보고 판단할 수 있으면 저기 위치를 출력해보는게 문제 해결을 위한 가장 빠른 방법이다.


s = r'[{"prodNo":374834551334,"prodNm":"나주곰탕 600g x 8인분","saleStatus":"A","salePrice":12500,"discountYn":"N","discountPrice":0,"optUseYn":"N","optTextList":[],"labelNoList":null,"mainImg":{"thumb":{"imgUrl":"","imgWidth":70,"imgHeight":70},"wide":{"imgUrl":"","imgWidth":580,"imgHeight":320},"largeImg":{"imgUrl":"","imgWidth":368,"imgHeight":368},"mediumImg":{"imgUrl":"","imgWidth":266,"imgHeight":266}},"mainYn":"Y","couponNm":null,"couponPrice":null,"couponPriceDispYn":"N"},{"prodNo":275632342448,"prodNm":"시원한 \\"갈비탕 600g x 4팩 8인분\\" 감칠맛","saleStatus":"A","salePrice":13900,"discountYn":"N","discountPrice":0,"optUseYn":"N","optTextList":[],"labelNoList":null,"mainImg":{"thumb":{"imgUrl":"","imgWidth":70,"imgHeight":70},"wide":{"imgUrl":"","imgWidth":580,"imgHeight":320},"largeImg":{"imgUrl":"","imgWidth":368,"imgHeight":368},"mediumImg":{"imgUrl":"","imgWidth":266,"imgHeight":266}},"mainYn":"N","couponNm":null,"couponPrice":null}]'
# data = json.loads(s)
print s[524:540]

를 해보면 '한 \\"갈비탕' 이라는게 출력되는데 눈치가 빠르면 \\때문에 이스케이핑이 잘못되었구나라고 깨달을 수 있다.


그런데 이런 방법으로도 뭔가 직관적이지 못하다면.


https://jsonlint.com/


여기에 넣어보는게 가장 속 편하다.

'Python > 2.7 information' 카테고리의 다른 글

why use namedtuple  (2) 2020.12.26
dictionary 예쁘게 출력하기 + 한글 그대로 출력  (0) 2019.10.23
timezone 설정 모듈.  (0) 2019.09.28
python re search with newline  (0) 2019.09.23
파일 옮기는 꿀팁. (SimpleHTTPServer)  (0) 2019.08.01