자바 스크립트 객체 대 JSON
Javascript 객체와 JSON 문자열의 기본 차이점을 명확하게 이해하고 싶습니다.
다음 JS 변수를 생성한다고 가정 해 봅시다.
var testObject = {one: 1,"two":2,"three":3};
Q1. 키 / 프로퍼티 이름이 따옴표를 포함하거나 포함하지 않고 모두 유효합니까? (예를 들어 "one" : 1
)
그렇다면 차이점은 무엇입니까?
Q2 :를 사용하여 위의 객체를 변환 JSON.stringify(testObject)
하면 원래 JS 객체와 JSON의 차이점은 무엇입니까?
나는 그들이 거의 같다고 생각합니다. 이것에 대해 자세히 설명하십시오.
Q3 : JSON 문자열을 구문 분석 할 때 아래 방법이 권장됩니까?
var javascriptObj = JSON.parse(jSonString);
-
키 / 프로퍼티 이름은 따옴표를 포함하거나 포함하지 않고 유효합니까?
키는 특수 문자를 (포함하는 경우 객체 리터럴 표기법을 사용할 때 따옴표로 키를 묶어야합니다 유일한 시간은
if
,:
,-
등). 그것은 JSON에 키가 있음을 주목할 가치가 있어야합니다 묶어야 이중 따옴표. -
를 사용하여 위의 객체를 JSON으로 변환하면
var jSonString = JSON.stringify(testObject);
2 (JS obj와 JSON)의 차이점은 무엇입니까?JSON 은 데이터 교환 형식입니다. 정렬 된 목록과 정렬되지 않은 맵, 문자열 부울 및 숫자를 문자열로 표현하는 방법을 설명하는 표준입니다. XML과 YAML이 언어간에 구조화 된 정보를 전달하는 방법 인 것처럼 JSON도 동일합니다. 반면에 JavaScript 객체는 물리적 유형입니다. C ++ 클래스 / 구조체 인 PHP 배열과 마찬가지로 JavaScript 객체는 JavaScript 내부의 유형입니다.
이야기가 있습니다. 상점에서 일부 가구를 구입했으며 배송을 원한다고 가정 해 봅시다. 그러나 재고가 남아있는 유일한 것은 디스플레이 모델이지만 귀하는 그것을 구매하기로 동의합니다.
상점에서 구입 한 서랍장은 살아있는 물건입니다.
var chestOfDrawers = { color: "red", numberOfDrawers: 4 }
그러나 게시물에 서랍장을 보낼 수 없으므로 게시물을 해체하십시오 (읽고 문자열 화). 이제는 가구면에서 쓸모가 없습니다. 이제 JSON입니다. 플랫 팩 형태입니다.
{"color":"red","numberOfDrawers":4}
당신이 그것을받을 때, 당신은 서랍장을 다시 작성 (읽고 구문 분석). 이제 객체 형태로 돌아 왔습니다.
JSON / XML 및 YAML의 이유는 프로그래밍 언어 사이에서 데이터를 모두 참여 언어가 이해할 수있는 형식으로 전송할 수 있기 때문입니다. PHP 또는 C ++에 JavaScript 객체를 직접 제공 할 수 없습니다. 각 언어는 실생활에서 다르게 개체를 나타 내기 때문입니다. 그러나 객체를 JSON 표기법으로 문자열 화했기 때문에; 즉, 데이터를 표현하는 표준화 된 방법으로 , 객체 의 JSON 표현 을 다른 언어 (C ++, PHP)로 전송할 수 있으며, 객체 의 JSON 표현을 기반 으로 자신의 객체로 JavaScript 객체를 다시 생성 할 수 있습니다 .
JSON은 함수 나 날짜를 나타낼 수 없습니다. 함수 멤버로 객체를 문자열 화하려고하면 JSON 표현에서 함수가 생략됩니다. 날짜는 문자열로 변환됩니다.
JSON.stringify({ foo: new Date(), blah: function () { alert('hello'); } }); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"
-
JSON 문자열을 구문 분석 할 때 아래 방법이 권장됩니까?
var javascriptObj = JSON.parse(jSonString);
예, 그러나 이전 브라우저는 기본적으로 JSON을 지원하지 않습니다 (IE <8) . 이를 지원하려면를 포함해야합니다
json2.js
.jQuery를 사용하는 경우을 호출 할 수 있습니다. 지원되는 경우 후드에서
jQuery.parseJSON()
사용JSON.parse()
되며 입력을 구문 분석하기 위해 사용자 정의 구현으로 대체됩니다.
Q1 : 자바 스크립트에서 객체 리터럴을 정의 할 때 키에 따옴표가 포함되거나 포함되지 않을 수 있습니다. 따옴표를 사용하면 인터프리터가 직접 시도하면 구문 분석에 실패하는 특정 키를 지정할 수 있다는 점을 제외하고는 차이가 없습니다. 예를 들어 느낌표 인 키를 원하면 따옴표가 필요합니다.
a = { "!": 1234 } // Valid
a = { !: 1234 } // Syntax error
그러나 대부분의 경우 객체 리터럴의 키 주위에 따옴표를 생략 할 수 있습니다.
Q2 : JSON은 문자 그대로 문자열 표현입니다. 그것은 단지 문자열입니다. 따라서 이것을 고려하십시오 :
var testObject = { hello: "world" }
var jSonString = JSON.stringify(testObject);
testObject
실제 객체 이므로 속성을 호출하고 객체로 할 수있는 다른 작업을 수행 할 수 있습니다.
testObject.hello => "world"
반면 jsonString
에 문자열은 다음과 같습니다.
jsonString.hello => undefined
또 다른 차이점에 유의하십시오. JSON에서는 모든 키를 따옴표로 묶어야합니다. 이는 Q1의 설명에 따라 일반적으로 따옴표를 생략 할 수있는 객체 리터럴과 대조됩니다.
Q3. You can parse a JSON string by using JSON.parse
, and this is generally the best way to do it (if the browser or a framework provides it). You can also just use eval
since JSON is valid javascript code, but the former method is recommended for a number of reasons (eval has a lot of nasty problems associated with it).
Problems solved by JSON
Let's say you want to exchange regular JavaScript objects between two computers, and you set two rules:
- The transmitted data must be a regular string.
- Only attributes can be exchanged, methods are not transmitted.
Now you create two objects on the first host:
var obj1 = { one: 1,"two":2,"three":3 }; // your example
var obj2 = { one: obj1.one, two: 2, three: obj1.one + obj1.two };
How can you convert those objects into strings for transmission to the second host?
- For the first object, you could send this string obtained form the literal definition
'{ one: 1,"two":2,"three":3 }'
, but actually you can't read the literal in the script portion of the document (at least not easily). Soobj1
andobj2
must actually be processed the same way. - You need to enumerate all attributes and their value, and build a string similar to the object literal.
JSON has been created as a solution to the needs just discussed: It is a set of rules to create a string equivalent to an object by listing all attributes and values (methods are ignored).
JSON normalizes the use of double-quotes for attribute names and values.
Remember that JSON is a set of rules only (a standard).
How many JSON objects are created?
Only one, it is automatically created by the JS engine.
Modern JavaScript engines found in browsers have a native object, also named JSON. This JSON object is able to:
Decode a string built using JSON standard, using JSON.parse(string). The result is a regular JS object with attributes and values found in the JSON string.
Encode attributes / values of a regular JS object using JSON.stringify(). The result is a string compliant with the JSON set of rules.
The (single) JSON object is similar to a codec, it's function is to encode and decode.
Note that:
JSON.parse() doesn't create a JSON object, it creates a regular JS object, there is no difference between an object created using an object literal and an object created by JSON.parse() from a JSON-compliant string.
There is only one JSON object, which is used for all conversions.
Going back to the questions:
Q1: The use of single of double quotes is allowed for object literals. Note that the quotes are used optionally for attributes names, and are mandatory for string values. The object literal itself is not surrounded by quotes.
Q2: Objects created from literals and using JSON.parse() are strictly the same. These two objects are equivalent after creation:
var obj1 = { one: 1, "two": 2, "three": 3 };
var obj2 = JSON.parse('{ "one": "1", "two": "2", "three": "3" }');
Q3: On modern browsers
JSON.parse()
is used to create a JS object from a JSON-compliant string. (jQuery has also an equivalent method that can be used for all browsers).
Q1 - in JS you only need to use quotes if the key is a reserved word or if it would otherwise be an illegal token. In JSON you MUST always use double quotes on key names.
Q2 - the jsonString
is a serialised version of the input object ...
Q3 - which may be deserialised to an identical looking object using JSON.parse()
Question already has good answers posted, I am adding a small example below, which will make it more easy to understand the explanations given in previous answers. Copy paste below snippet to your IDE for better understanding and comment the line containing invalid_javascript_object_no_quotes
object declaration to avoid compile time error.
// Valid JSON strings(Observe quotes)
valid_json = '{"key":"value"}'
valid_json_2 = '{"key 1":"value 1"}' // Observe the space(special character) in key - still valid
//Valid Javascript object
valid_javascript_object_no_quotes = {
key: "value" //No special character in key, hence it is valid without quotes for key
}
//Valid Javascript object
valid_javascript_object_quotes = {
key:"value", //No special character in key, hence it is valid without quotes for key
"key 1": "value 1" // Space (special character) present in key, therefore key must be contained in double quotes - Valid
}
console.log(typeof valid_json) // string
console.log(typeof valid_javascript_object_no_quotes) // object
console.log(typeof valid_javascript_object_quotes) // object
//Invalid Javascript object
invalid_javascript_object_no_quotes = {
key 1: "value"//Space (special character) present in key, since key is not enclosed with double quotes "Invalid Javascript Object"
}
참고URL : https://stackoverflow.com/questions/8294088/javascript-object-vs-json
'Programing' 카테고리의 다른 글
git stash blunder : git stash pop은 병합 충돌로 끝났습니다. (0) | 2020.05.10 |
---|---|
jQuery에서 live ()를 on ()으로 바꾸기 (0) | 2020.05.10 |
파이썬 문자열에서 u 접두사는 무엇입니까? (0) | 2020.05.10 |
C ++에서 <=> 연산자는 무엇입니까? (0) | 2020.05.10 |
Context.startForegroundService ()가 Service.startForeground ()를 호출하지 않았습니다. (0) | 2020.05.10 |