TIL. 61 Javascript JSON.parse(), JSON.stringify() 사용하는 법

조윤식·2022년 9월 13일
0

오늘은 자바스크립트의 메소드인 JSON.parse()와 JSON.stringify()에 대해 알아보겠습니다.

JSON.parse()란?

parse 메소드는 string 객체를 json 객체로 변환시켜줍니다.

JSON.stringify( )는 자바스크립트의 값을 JSON 문자열로 변환한다.

JSON이란?

JSON은 JavaScript Object Notation의 약자로, 브라우저와 서버사이에서 오고가는 데이터의 형식이다.

JSON.stringify(value, replacer, space)

value(필수): JSON 문자열로 변환할 값이다.(배열, 객체, 또는 숫자, 문자 등이 될 수 있다.)

replacer(선택): 함수 또는 배열이 될 수 있다. 이 값이 null 이거나 제공되지 않으면, 객체의 모든 속성들이 JSON 문자열 결과에 포함된다.

[함수일 때]

문자열화 프로세스의 작동을 변경하는 함수로 사용할 수 있다.

문자열화 될 key와 value, 2개의 매개변수를 받는다.

Example 1)

var data = {

    Name: "SooYoung"

    , Age: "27"

}



var person = JSON.stringify(data);

var oPerson = JSON.parse(person);



//output

alert(person);

/* Output: "{"Name":"SooYoung","Age":"29"}" */

alert(oPerson);

/* Output: Object */

Example 2)

function signup()

{

	var member = {

		"email": "test@naver.com",

		"password": "1234"

	};

	

	$.ajax({

		url : '/account/signup',

		dataType : 'json',

		type : 'POST',

		data : JSON.stringify(member), //그냥 member 사용하면 error 발생!

		contentType : 'application/json; charset=UTF-8',

		success : function(result) {

//TODO

			console.log(result);

		}

	});

}
@RequestMapping(value = "/signup", method = RequestMethod.POST)

public MemberResultDto signup(@RequestBody Member member)  

{                         

	systemLog.info("try to sign up..");

//TODO

	return memberResultDto;

}

@RequestBody는 HTTP요청의 body 내용을 자바 객체로 매핑 하는 역할을 합니다.

profile
Slow and steady wins the race

0개의 댓글