본문 바로가기
Programming/Error

Uncaught SyntaxError: Unexpected token o in JSON at position 1 - 리턴받은 데이터를 JSON.parse()하면서 생긴 오류

by 구튼탁 2021. 1. 16.
728x90

수정 전

ajax로 데이터를 요청한 후, 서버에서 넘어온 데이터를 JSON.parse(data) 해주려고 했다.

서버에서 return 타입을 map으로 했기 때문에 자바스크립트에서 json 객체로 데이터를 다루려면

JSON객체로 파싱해줘야 되는 것으로 착각했다. 

//자바스크립트
function getListNearMe(item){
			$.ajax({
				url : './getNearXY',
				data : {'x' : item.x, 'y' : item.y},
				contentType : 'json',
				success : function(data){
					alert('성공')
					var data = JSON.parse(data);
				},
				error : function(data){
					alert('실패')
				}				
			});
		}

// spring 
@RequestMapping(value="getNearXY")
	public @ResponseBody Map<String, Object> listByRadius(@RequestParam("x") String x, @RequestParam("y") String y){

		List<PoliceVO> vo = lostService.getSimpleList(x, y);
        
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("police", vo);
		
		return map;
	}

 

원인

이미 json object로 데이터가 넘어왔는데 JSON.parse()으로 파싱을 한 게 문제였다. 

왜냐하면

출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

JSON.parse()는 json 구조로 된 문자열 json 객체로 파싱해주는 것이기 때문이다. 

 

위 사진처럼 JSON 객체를 JSON.parse() 인자로 전달하면 region_type 등에 문자열 기호 ''가 없기 때문에

Unexpected token 에러를 발생시킨 것이다. 

 

수정 후 

JSON.parse() 하지 않고 그냥 사용하면 된다.

728x90

댓글