|
||||||
JSON(JavaScript Object Notation)
자바스크립트의 표기법으로 자바스크립트가 탄생했을 때부터 존재해왔던 방식
데이터 양이 많이 줄고 객체 접근과 문자열 객체 방식이 편리한 사용방식이라서 대부분의
오픈 API에서 JSON 형식의 데이타를 크게 지원해주고 있음
아래 글의 출처는 http://ko.wikipedia.org/wiki/JSON http://en.wikipedia.org/wiki/JSON 입니다.
JSON(제이슨, JavaScript Object Notation)은, 인터넷에서 자료를 주고받을 때 그 자료를 표현하는 방법이다. 자료의 종류에 큰 제한은 없으며, 특히 컴퓨터 프로그램의 변수값을 표현하는 데 적합하다.
그 형식은 자바스크립트의 구문 형식을 따르지만, 프로그래밍 언어나 플랫폼에 독립적이므로 C, C++, 자바, 자바스크립트, 펄, 파이썬 등 많은 언어에서 이용할 수 있다.
RFC 4627로 규격화되었다.
문법
JSON 문법은 자바스크립트 표준인 ECMA-262 3판의 객체 문법에 바탕을 두며, 인코딩은 유니코드로 한다. 표현할 수 있는 자료형에는 수, 문자열, 참/거짓이 있고, 또 배열과 객체도 표현할 수 있다.
배열은 대괄호로 나타낸다. 배열의 각 요소는 기본자료형이거나 배열, 객체이다.
[10, {"v": 20}, [30, "마흔"]]
객체는 이름/값 쌍의 집합으로, 중괄호로 싼다. 이름은 문자열이기 때문에 반드시 따옴표를 하며, 값은 기본자료형이거나 배열, 객체이다. 각 쌍이 나오는 순서는 의미가 없다.
{"name2": 50, "name3": "값3", "name1": true}
아래와 같이 이름에 따옴표를 쓰지 않아도 상관 없지만, 쓰는 편이 문자열과 숫자를 구분하기 좋다.
{name2: 50, name3: "값3", name1: true}
JSON 메시지 단위는 배열이나 객체이다. 위의 두 예는 JSON 메시지가 될 수 있다.
예제
다음은 한 사람에 관한 정보를 갖는 JSON 객체이다.
{ "이름": "테스트", "나이": 25, "성별": "여", "기혼": true, "주소": "서울특별시 양천구 목동", "특기": ["농구", "도술"], "가족관계": {"#": 2, "아버지": "홍판서", "어머니": "춘섬"} "회사": "경기 안양시 만안구 안양7동" }
장점
JSON은 텍스트로 이루어져 있으므로, 사람과 기계 모두 읽고 쓰기 쉽다.
프로그래밍 언어와 플랫폼에 독립적이므로, 서로 다른 시스템간에 객체를 교환하기에 좋다.
자바스크립트의 문법을 채용했기 때문에, 자바스크립트에서 eval 명령으로 곧바로 사용할 수 있다. 이런 특성은 자바스크립트를 자주 사용하는 웹 환경에서 유리하다.
JSON (an acronym for JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for virtually every programming language.
The JSON format was originally specified by Douglas Crockford, and is described in RFC 4627. The official Internet media type for JSON is application/json. The JSON filename extension is .json.
The JSON format is often used for serializing and transmitting structured data over a network connection. It is primarily used to transmit data between a server and web application, serving as an alternative to XML.
History
Douglas Crockford was the first to specify and popularize the JSON format.
JSON was used at State Software, a company co-founded by Crockford, starting around 2001. The JSON.org website was launched in 2002. In December 2005, Yahoo! began offering some of its web services in JSON. Google started offering JSON feeds for its GData web protocol in December 2006.
Although JSON was based on a subset of the JavaScript programming language (specifically, Standard ECMA-262 3rd Edition—December 1999) and is commonly used with that language, it is considered to be a language-independent data format. Code for parsing and generating JSON data is readily available for a large variety of programming languages. json.org provides a comprehensive listing of existing JSON libraries, organized by language.
Data types, syntax and example
JSON's basic types are:
- Number (integer or real)
- String (double-quoted Unicode with backslash escaping)
- Boolean (
trueorfalse) - Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
- Object (a collection of key:value pairs, comma-separated and enclosed in curly braces)
null
The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person's address, and contains a list (an array) of phone number objects.
{ "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }
A possible equivalent for the above in XML could be:
<Person firstName="John" lastName="Smith" age="25"> <address streetAddress="21 2nd Street" city="New York" state="NY" postalCode="10021"/> <phoneNumber type="home">212 555-1234</phoneNumber> <phoneNumber type="fax">646 555-4567</phoneNumber> </Person>
Since JSON is a subset of JavaScript it is possible (but not recommended) to parse the JSON text into an object by invoking JavaScript's eval() function. For example, if the above JSON data is contained within a JavaScript string variable contact, one could use it to create the JavaScript object p like so:
var p = eval("(" + contact + ")");
The contact variable must be wrapped in parentheses to avoid an ambiguity in JavaScript's syntax.
The recommended way, however, is to use a JSON parser. Unless a client absolutely trusts the source of the text, or must parse and accept text which is not strictly JSON-compliant, one should avoid eval(). A correctly implemented JSON parser will accept only valid JSON, preventing potentially malicious code from running.
Modern browsers, such as Firefox 3.5 and Internet Explorer 8, include special features for parsing JSON. As native browser support is more efficient and secure than eval(), it is expected that native JSON support will be included in the next ECMAScript standard.
JSON schema
There are several ways to verify the structure and data types inside a JSON object, much like an XML schema.
JSON Schema is a specification for a JSON-based format for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how it can be modified, much like what XML Schema provides for XML. JSON Schema is intended to provide validation, documentation, and interaction control of JSON data. JSON Schema is based on the concepts from XML Schema, RelaxNG, and Kwalify, but is intended to be JSON-based, so that JSON data in the form of a schema can be used to validate JSON data, the same serialization/deserialization tools can be used for the schema and data, and it can be self descriptive.
Using JSON in Ajax
The following JavaScript code shows how the client can use an XMLHttpRequest to request an object in JSON format from the server. (The server-side programming is omitted; it has to be set up to respond to requests at url with a JSON-formatted string.)
var the_object = {}; var http_request = new XMLHttpRequest(); http_request.open( "GET", url, true ); http_request.onreadystatechange = function () { if (http_request.readyState == 4 && http_request.status == 200){ the_object = JSON.parse( http_request.responseText ); } }; http_request.send(null);
Note that the use of XMLHttpRequest in this example is not cross-browser compatible; syntactic variations are available for Internet Explorer, Opera, Safari, and Mozilla-based browsers. The usefulness of XMLHttpRequest is limited by the same origin policy: the URL replying to the request must reside within the same DNS domain as the server that hosts the page containing the request. Alternatively, the JSONP approach incorporates the use of an encoded callback function passed between the client and server to allow the client to load JSON-encoded data from third-party domains and to notify the caller function upon completion, although this imposes some security risks and additional requirements upon the server.
Browsers can also use <iframe> elements to asynchronously request JSON data in a cross-browser fashion, or use simple <form action="url_to_cgi_script" target="name_of_hidden_iframe"> submissions. These approaches were prevalent prior to the advent of widespread support for XMLHttpRequest.
Dynamic <script> tags can also be used to transport JSON data. With this technique it is possible to get around the same origin policy but it is insecure. JSONRequest has been proposed as a safer alternative.
Comparison with other formats
XML
XML
is often used to describe structured data and to serialize objects. Various XML-based protocols exist to represent the same kind of data structures as JSON for the same kind of data interchange purposes.
When data is encoded in XML, the result is typically larger in size than an equivalent encoding in JSON, mainly because of XML's closing tags. For example, ignoring irrelevant white space, the JSON encoding above for the "John Smith" data consumes 240 characters whereas the XML encoding consumes 313 characters. In this particular example, the XML encoding requires just over 30% more characters.
However, there are alternative ways to encode the same information. For example, XML allows the encoding of information in attributes, which are enclosed in quotes and thus have no end tags. Using attributes, an alternative XML encoding of the "John Smith" information is as follows:
<Person firstName='John' lastName='Smith' age='25' > <address streetAddress='21 2nd Street' city='New York' state='NY' postalCode='10021' /> <phoneNumbers home='212 555-1234' fax='646 555-4567' /> </Person>
Not counting the irrelevant white-space, and ignoring the required XML header, this XML encoding only requires 200 characters, whereas the comparable JSON encoding requires 209 characters. The XML encoding can therefore be shorter than the equivalent JSON encoding.
Beyond size, both XML and JSON lack an explicit mechanism for representing large binary data types such as image data (although binary data can be serialized in either case by applying a general-purpose binary-to-text encoding scheme). JSON lacks references (something XML has via extensions like XLink and XPointer) and has no standard path notation comparable to XPath.
YAML
Both functionally and syntactically, YAML is effectively a superset of JSON. The common YAML library (Syck) also parses JSON. Prior to YAML version 1.2, YAML was not quite a perfect superset of JSON, primarily because it lacked native handling of UTF-32 and required comma separators to be followed by a space.
The most distinguishing point of comparison is that YAML offers the following syntax enrichments which have no corresponding expression in JSON:
- Relational:
- YAML offers syntax for relational data: rather than repeating identical data later in a document, a YAML document can refer to an anchor earlier in the file/stream. Recursive structures (for example, an array containing itself) can be expressed this way. For example, a film data base might list actors (and their attributes) under a Movie's cast, and also list Movies (and their attributes) under an Actor's portfolio.
- Extensible:
- YAML also offers extensible data types beyond primitives (i.e., strings, floats, ints, bools) which can include class-type declarations.
- Blocks:
- YAML uses a block-indent syntax to allow formatting of structured data without use of additional characters (ie: braces, brackets, quotation marks, etc.). Besides giving YAML a different appearance than JSON, this block-indent device permits the encapsulation of text from other markup languages or even JSON in the other languages native literal style and without escaping of colliding sigils.
JSONP
JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.
Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is HTML <script> tags. Taking advantage of the open policy for <script> tags, some pages use them to retrieve JSON from other origins.
To see how that works, let's consider a URL that, when requested, returns a JSON statement. In other words, a browser requesting the URL would receive something like:
{"Name": "Cheeso", "Rank": 7}
The Basic Idea: Retrieving JSON via Script Tags
It's possible to specify any URL, including a URL that returns JSON, as the src attribute for a <script> tag.
Specifying a URL that returns plain JSON as the src-attribute for a script tag, would embed a data statement into a browser page. It's just data, and when evaluated within the browser's javascript execution context, it has no externally detectable effect.
One way to make that script have an effect is to use it as the argument to a function. invoke( {"Name": "Cheeso", "Rank": 7}) actually does something, if invoke() is a function in Javascript.
And that is how JSONP works. With JSONP, the browser provides a JavaScript "prefix" to the server in the src URL for the script tag; by convention, the browser provides the prefix as a named query string argument in its request to the server, e.g.,
<script type="text/javascript" src="http://server2.example.com/getjson?jsonp=parseResponse"> </script>
The server then wraps its JSON response with this prefix, or "padding", before sending it to the browser. When the browser receives the wrapped response from the server it is now a script, rather than simply a data declaration. In this example, what is received is
parseResponse({"Name": "Cheeso", "Rank": 7})
...which can cause a change of state within the browser's execution context, because it invokes a method.
The Padding
While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other Javascript statement prefix.
Script Tag Injection
But to make a JSONP call, you need a script tag. Therefore, for each new JSONP request, the browser must add a new <script> tag -- in other words, inject the tag -- into the HTML DOM, with the desired value for the src attribute. This element is then evaluated, the src URL is retrieved, and the response JSON is evaluated.
In that way, the use of JSONP can be said to allow browser pages to work around the same origin policy via script tag injection.
Basic Security concerns
Because JSONP makes use of script tags, calls are essentially open to the world. For that reason, JSONP may be inappropriate for carrying sensitive data.
Including script tags from remote sites allows the remote sites to inject any content into a website. If the remote sites have vulnerabilities that allow JavaScript injection, the original site can also be affected.
Cross-site request forgery
Naïve deployments of JSONP are subject to cross-site request forgery attacks (CSRF or XSRF). Because the HTML <script> tag does not respect the same origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.
This is only a problem if the JSON-encoded data contains sensitive information that should not be disclosed to a third party, and the server depends on the browser's Same Origin Policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself, only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery.
History
The original proposal for JSONP appears to have been made by Bob Ippolito in 2005 and is now used by many Web 2.0 applications such as Dojo Toolkit Applications, Google Web Toolkit Applications and Web Services. Further extensions of this protocol have been proposed by considering additional input arguments as, for example, is the case of JSONPP supported by S3DB web services.
![]() |
![]() |
































