From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../reference/global_objects/json/index.html | 122 +++++++++++ .../reference/global_objects/json/parse/index.html | 123 +++++++++++ .../global_objects/json/stringify/index.html | 230 +++++++++++++++++++++ 3 files changed, 475 insertions(+) create mode 100644 files/ko/web/javascript/reference/global_objects/json/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/stringify/index.html (limited to 'files/ko/web/javascript/reference/global_objects/json') diff --git a/files/ko/web/javascript/reference/global_objects/json/index.html b/files/ko/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..ef21cfc534 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,122 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef}}
+ +

JSON 객체는 JavaScript Object Notation({{glossary("JSON")}})을 분석하거나 값을 JSON으로 변환하는 메서드를 가지고 있습니다. JSON을 직접 호출하거나 인스턴스를 생성할 수 없으며, 두 개의 메서드를 제외하면 자신만의 흥미로운 기능은 없습니다.

+ +

JavaScript와 JSON의 차이

+ +

JSON은 객체, 배열, 숫자, 문자열, 불리언과 {{jsxref("null")}}을 직렬화하기 위한 구문으로, JavaScript 구문에 기반을 두고 있지만 분명한 차이점을 가지고 있습니다. 즉, 어떤 JavaScript는 JSON이 아닙니다.

+ +
+
객체와 배열
+
속성의 이름은 반드시 큰따옴표로 표시된 문자열이어야 합니다. 후행 쉼표는 허용하지 않습니다.
+
숫자
+
선행 0은 허용하지 않습니다. 소숫점 뒤에는 적어도 한 자릿수가 뒤따라야 합니다. {{jsxref("NaN")}}과 {{jsxref("Infinity")}}는 지원하지 않습니다.
+
모든 JSON 텍스트는 유효한 JavaScript 표현식...
+
...이지만, 모든 JSON 텍스트를 올바른 ECMA-262로 만드는 제안을 구현한 JavaScript 엔진에서만 그러합니다. 다른 엔진에서는, U+2028 LINE SEPARATOR와 U+2029 PARAGRAPH SEPARATOR를 JSON에서 스트링 리터럴과 속성의 키로 사용할 수 있지만, JavaScript 문자열 리터럴에서 사용하면 {{jsxref("SyntaxError")}}가 발생합니다.
+
+ +

{{jsxref("JSON.parse()")}}로 JSON 문자열을 분석하고 {{jsxref("eval")}}이 JavaScript 문자열로 실행하는 다음 예시를 참고하세요.

+ +
const code = '"\u2028\u2029"'
+JSON.parse(code) // 모든 엔진에서 "\u2028\u2029"로 평가
+eval(code)       // 오래된 엔진에서 SyntaxError
+
+ +

다른 차이점으로는 문자열의 작은따옴표 금지와, 주석 및 {{jsxref("undefined")}} 미지원이 있습니다. JSON에 기반한, 보다 사람 친화적인 설정 형식을 원하면 Babel 컴파일러가 사용하는 JSON5가 있고, 좀 더 많이 쓰이는 YAML도 있습니다.

+ +

전체 JSON 구문

+ +
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+ +

중요하지 않은 공백은 JSONNumber(숫자에는 공백이 없어야 함) 또는 JSONString(문자열에서 해당 문자로 해석되거나 오류를 일으킴) 내를 제외하고 어디에나 존재할 수 있습니다. 탭 문자(U+0009), 캐리지 리턴(U+000D), 라인 피드(U+000A) 및 스페이스(U+0020) 문자만이 유효한 공백 문자입니다.

+ +

메서드

+ +
+
{{jsxref("JSON.parse()")}}
+
문자열을 JSON으로서 구문 분석하고, 선택적으로 분석 결과의 값과 속성을 변환해 반환합니다.
+
{{jsxref("JSON.stringify()")}}
+
주어진 값에 해당하는 JSON 문자열을 반환합니다. 선택 사항으로 특정 속성만 포함하거나 사용자 정의 방식으로 속성을 대체합니다.
+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.JSON")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/json/parse/index.html b/files/ko/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..fa32b3711e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,123 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript 5 + - JSON + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +
{{JSRef}}
+ +

JSON.parse() 메서드는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다. 선택적으로, reviver 함수를 인수로 전달할 경우, 결과를 반환하기 전에 변형할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/json-parse.html")}}
+ + + +

구문

+ +
JSON.parse(text[, reviver])
+ +

매개변수

+ +
+
text
+
JSON으로 변환할 문자열. JSON 구문은 {{jsxref("JSON")}} 객체의 설명을 참고하세요.
+
reviver {{optional_inline}}
+
함수라면, 변환 결과를 반환하기 전에 이 인수에 전달해 변형함.
+
+ +

반환 값

+ +

주어진 JSON 문자열에 대응하는 {{jsxref("Object")}}.

+ +

예외

+ +

변환할 문자열이 유효한 JSON이 아닐 경우 {{jsxref("SyntaxError")}}.

+ +

예제

+ +

JSON.parse() 사용하기

+ +
JSON.parse('{}');              // {}
+JSON.parse('true');            // true
+JSON.parse('"foo"');           // "foo"
+JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
+JSON.parse('null');            // null
+
+ +

reviver 매개변수 사용하기

+ +

reviver가 주어지면 분석한 값을 반환하기 전에 변환합니다. 구체적으로는, 분석한 값과 그 모든 속성(가장 깊게 중첩된 속성부터 시작해 제일 바깥의 원래 값까지)을 각각 reviver에 전달합니다. reviver의 this 문맥은 분석한 값으로 설정되고, 속성 명(문자열)과 값을 인자로 전달받습니다. reviver가 {{jsxref("undefined")}}를 반환하거나 반환하지 않는다면, 예컨대 함수가 중간에 실패한다면 그 속성은 최종 결과에서 제외됩니다. 그 외에는 반환 값으로 속성의 값을 재설정합니다.

+ +

만약 reviver가 일부 값만 변환하고 나머지는 건드리지 않는다면, 나머지 값을 그대로 반환하는걸 잊지 마세요. 그렇지 않으면 변환한 값 외에는 결과에서 모두 제외됩니다.

+ +
JSON.parse('{"p": 5}', (key, value) =>
+  typeof value === 'number'
+    ? value * 2 // 숫자라면 2배
+    : value     // 나머진 그대로
+);
+
+// { p: 10 }
+
+JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
+  console.log(key); // 현재 속성명 출력, 마지막은 빈 문자열("")
+  return value;     // 변환하지 않고 그대로 반환
+});
+
+// 1
+// 2
+// 4
+// 6
+// 5
+// 3
+// ""
+ +

후행 쉼표 사용 불가

+ +
// 둘 다 SyntaxError
+JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.JSON.parse")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/json/stringify/index.html b/files/ko/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..12de82705b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,230 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +tags: + - JSON + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +
{{JSRef}}
+ +

JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다. 선택적으로, replacer를 함수로 전달할 경우 변환 전 값을 변형할 수 있고, 배열로 전달할 경우 지정한 속성만 결과에 포함합니다.

+ +
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
+ + + +

구문

+ +
JSON.stringify(value[, replacer[, space]])
+ +

매개변수

+ +
+
value
+
JSON 문자열로 변환할 값.
+
replacer {{optional_inline}}
+
문자열화 동작 방식을 변경하는 함수, 혹은 JSON 문자열에 포함될 값 객체의 속성들을 선택하기 위한 화이트리스트(whitelist)로 쓰이는 {{jsxref("String")}} 과 {{jsxref("Number")}} 객체들의 배열. 이 값이 null 이거나 제공되지 않으면, 객체의 모든 속성들이 JSON 문자열 결과에 포함된다.
+
+ +
+
space {{optional_inline}}
+
가독성을 목적으로 JSON 문자열 출력에 공백을 삽입하는데 사용되는 {{jsxref("String")}} 또는 {{jsxref("Number")}} 객체. 이것이 Number 라면, 공백으로 사용되는 스페이스(space)의 수를 나타낸다; 이 수가 10 보다 크면 10 으로 제한된다. 1 보다 작은 값은 스페이스가 사용되지 않는 것을 나타낸다. 이것이 String 이라면, 그 문자열(만약 길이가 10 보다 길다면, 첫번째 10 개의 문자)이 공백으로 사용된다. 이 매개 변수가 제공되지 않는다면(또는 null 이면), 공백이 사용되지 않는다.
+
+ +

반환 값

+ +

주어진 값과 대응하는 JSON 문자열.

+ +

예외

+ +

순환 참조를 발견할 경우 {{jsxref("TypeError")}}(cyclic object value).

+ +

설명

+ +

JSON.stringify()는 값을 JSON 표기법으로 변환한다.

+ + + +
JSON.stringify({});                  // '{}'
+JSON.stringify(true);                // 'true'
+JSON.stringify('foo');               // '"foo"'
+JSON.stringify([1, 'false', false]); // '[1,"false",false]'
+JSON.stringify({ x: 5 });            // '{"x":5}'
+
+JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
+// '"2006-01-02T15:04:05.000Z"'
+
+JSON.stringify({ x: 5, y: 6 });
+// '{"x":5,"y":6}' or '{"y":6,"x":5}'
+JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
+// '[1,"false",false]'
+
+// Symbols:
+JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
+// '{}'
+JSON.stringify({ [Symbol('foo')]: 'foo' });
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
+  if (typeof k === 'symbol') {
+    return 'a symbol';
+  }
+});
+// '{}'
+
+// Non-enumerable properties:
+JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
+// '{"y":"y"}'
+
+
+ +

replacer 매개 변수

+ +

replacer 매개변수는 함수 또는 배열이 될 수 있다. 함수일 때는 문자열화 될 key 와 value, 2개의 매개변수를 받는다. key 가 발견된 객체는 리플레이서의 this 매개변수로 제공된다. 맨 처음에는 문자열화될 그 객체를 나타내는 비어 있는 key와 함께 호출되고, 그 다음에는 문자열화될 그 객체나 배열의 각 속성에 대해 호출된다. 이것은 JSON 문자열에 추가되어야 하는 값을 반환해야한다:

+ + + +
유의: replacer 함수를 배열로부터 값을 제거하기위해 사용할 수 없다. 만약 undefined 나 함수를 반환한다면 null 이 대신 사용될 것이다.
+ +

함수에 대한 예제

+ +
function replacer(key, value) {
+  if (typeof value === "string") {
+    return undefined;
+  }
+  return value;
+}
+
+var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
+var jsonString = JSON.stringify(foo, replacer);
+
+ +

JSON 문자열 결과는 {"week":45,"month":7} 이다.

+ +

배열에 대한 예제

+ +

replacer 가 배열인 경우, 그 배열의 값은 JSON 문자열의 결과에 포함되는 속성의 이름을 나타낸다.

+ +
JSON.stringify(foo, ['week', 'month']);
+// '{"week":45,"month":7}', 단지 "week" 와 "month" 속성을 포함한다
+
+ +

space 매개 변수

+ +

space 매개변수는 최종 문자열의 간격을 제어한다. 숫자일 경우 최대 10자 만큼의 공백 문자 크기로 들여쓰기되며, 문자열인 경우 해당 문자열 또는 처음 10자 만큼 들여쓰기 된다.

+ +
JSON.stringify({ a: 2 }, null, ' ');
+// '{
+//  "a": 2
+// }'
+
+ +

'\t'를 사용하면 일반적으로 들여쓰기 된 코드스타일과 유사함.

+ +
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
+// returns the string:
+// '{
+//     "uno": 1,
+//     "dos": 2
+// }'
+
+ +

toJSON() 작동

+ +

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. For example:

+ +
var obj = {
+  foo: 'foo',
+  toJSON: function() {
+    return 'bar';
+  }
+};
+JSON.stringify(obj);        // '"bar"'
+JSON.stringify({ x: obj }); // '{"x":"bar"}'
+
+ +

Example of using JSON.stringify() with localStorage

+ +

In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify():

+ +
+

Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like {{jsxref("Date")}} will be a string after {{jsxref("JSON.parse()")}}.

+
+ +
// Creating an example of JSON
+var session = {
+  'screens': [],
+  'state': true
+};
+session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
+session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
+session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
+session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
+session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
+session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
+
+// Converting the JSON string with JSON.stringify()
+// then saving with localStorage in the name of session
+localStorage.setItem('session', JSON.stringify(session));
+
+// Example of how to transform the String generated through
+// JSON.stringify() and saved in localStorage in JSON object again
+var restoredSession = JSON.parse(localStorage.getItem('session'));
+
+// Now restoredSession variable contains the object that was saved
+// in localStorage
+console.log(restoredSession);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.JSON.stringify")}}

+ +

같이 보기

+ + -- cgit v1.2.3-54-g00ecf