블로그 운영자의 샵포탈 쇼핑몰

사이렌24(리워드불가)

.com .net .co.kr .org .cn
.name .biz .info .tv .cc

.kr .com .net .org  

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:

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.

크리에이티브 커먼즈 라이선스
Creative Commons License

블로그코리아에 블UP하기

Share |

Posted by vermouth

Super Tc`Blog Super Ts´Blog API 멀티 블로거 (6개 블로그멀티등록) NiceProxy 아이룩(iLook) Smart VPN (스마트VPN) 직장인을 위한 주식 자동매매 프로그램
이미지 자동 검색/다운로더 이미지 썸네일 생성기 My Love Car Ver1.0b 스팟 (사생활 보호 프로그램) EasyMan FF Lock 키즈키퍼
성공공간 Utility Projects 2 (원클릭 원유틸) OkStock4U OkBar4U OkDM4U QuickMonitor QuickMenu
FastKey (윈도우 단축키 매니저) 열혈영어 눈치코치 RManager (1:N 원격제어) 똑똑이-프리미엄 ezManager@모아모아 비쥬얼 인벤토리 for Delivery
EasyProxy(이지프록시) 수출가격산출 프로그램 고객관리 프로그램 RTAM (알탐) 도서관리 프로그램 폴더 감추기 부가가치세 관리 프로그램
다국어 번역기 레시피 매니저 JJangCalendar 국세청 사업자 과세유형 및 휴폐업 조회 프로그램 EURUSD_Signal_B 쇼핑몰 관리매니저 - 오토퀘스쳔 QNA24 - 쇼핑몰 문의글 관리(Cafe24쇼핑몰 전용)
개구멍 - 회사에서 네이트온, 주식, 웹서핑을 자유롭게! 회사 방화벽 뚫기/해제 프로그램 다모아 (damoa) - 실시간 자동 파일 백업 프로그램 (각종 문서/그래픽/개발툴 파일) OkPL4U - BOM 및 자재 입.출고, 생산, 재고관리 오피셜키퍼 - 사무실/학원 원격관리 및 모니터링프로그램 쉽고 강력한 파일 암호화 보호 프로그램 심플락(Simple Lock) 노래방, 노래주점 매장관리 프로그램 송맨XE(SongMan XE) 직장인 프라이버시 보호 프로그램 누가봐?
모니터 화면 돋보기 프로그램 다보여 PS2 키보드 제어 매크로 프로그램 Mini Key Macro 업무 보조 프로그램! 여러가지 기능을 하나로! 미니 펑~☆ 당좌거래정지자 조회프로그램 당좌거래오피스 Access, MS-SQL, ORACLE 서버에 접속하여 통합적으로 쿼리를 분석 SQL 통합쿼리분석기 이미지 크기, 포맷, 용량 줄이기 이미지 파일 변환 프로그램 파워포인트 파일을 전자책(e-Book) & 포토북으로 변환시켜 주는 프로그램 전자책(e-Book) & 포토북 제작 프로그램
IP 자동 변경 프로그램 IPAutoChanger 이미지 다운로드 프로그램 이미지리더2.0 설정하기 쉬운 메크로! 미찌 메크로 사용자가 지정한 파일을 보호한다! 파일 프로텍터(File Protecter) 하드디스크 읽기쓰기 모니터링 다알아 플래시 광고, 배너 광고, 리치미디어, 슬라이드인과 플라이인과 같은 웹 사이트의 모든 종류의 광고를 차단하는 광고팍팍! 다수의 IP를 실시간 체크하는 핑 테스터 EZ PING (연결 상태 모니터링)
PC-Ghost 다중 실시간 원격 모니터링 프로그램 작업중인 문서파일을 자동수집/백업하는 프로그램 다모아 내 쇼핑몰의 상품을 자동으로 블로그와 카페에 포스팅해 주는 프로그램 Mall Admin 데이타베이스 온라인 예약백업 DamoaDB 간편한 QRcode 생성 및 인쇄 프로그램 OkQrCode BOM 및 자재 입.출고, 생산, 재고관리 프로그램 OkPL4U 양음LIVE 주식리딩 생방송 양음선생의 차트알박기
쉽고 빠른 재고 관리 프로그램!! 마이플랜(중소기업,개인사업자용) 윈도우 바탕화면을 주기적으로 바꾸자 Chameleon 2.0 간편고객 및 판매 관리 (문자(SMS), 주소 봉투/라벨인쇄, 메일주소 추출 지원) OkCRM4U 스마트 마케터 (대량메일발송) 대량 e메일(DM) 발송 프로그램 슈퍼 메일러 트위터 자동 트윗


BLOG main image
무궁무진한 프로그래밍의 세계!! by vermouth

카테고리

분류 전체보기 (3788)
자작 프로그램들 (4)
자작 IT 번역문서 (0)
IT 이야기 (134)
IT 영어 회화 (9)
IT 프리랜서 (50)
블로그 포스팅 마케팅 리뷰 (35)
하드웨어 튜닝 (114)
컴퓨터 튜닝 (22)
취약점과 버그 (117)
아이폰(iPhone), 아이팟(iPod) (32)
애플 앱스토어(Apple App Sto.. (4)
맥 앱스토어(Mac App Store) (2)
구글 애드센스(Google Adsense) (121)
구글 애드몹(Google AdMob) (76)
애플 아이애드(Apple iAd) (8)
애플 아이북스 스토어(Apple.. (5)
구글 이북 스토어(Google eBo.. (1)
구글 웹로그 분석기(Google A.. (15)
오픈 공개소스 (57)
오픈소스 라이센스 (14)
오픈 API(Open API) (40)
버전 관리 (10)
소프트웨어 사용팁 (6)
응용 프로그래밍 언어 (217)
웹 프로그래밍 언어 (179)
스크립트 언어 (76)
애플리케이션 (5)
데이타베이스 서버 프로그래밍 (156)
마크업언어 정의언어 (189)
닷넷 (47)
운영체제와 서버 (207)
모바일 운영체제 (266)
타블렛 PC(Tablet PC) (25)
리치 인터넷 애플리케이션(Ri.. (13)
매쉬업(mashup) (15)
디바이스드라이버 개발 (53)
하드웨어 프로그래밍 (13)
웹사이트 홍보와 관리 (18)
소프트웨어 개발 방법론 (2)
클라우드 컴퓨팅(Cloud Compu.. (141)
데이타센타 구축 기술(Datace.. (5)
아키텍처와 알고리즘 (67)
데이타베이스 설계 (11)
오픈 소스 프레임워크 (18)
아파치 소프트웨어 재단(Apac.. (5)
닷넷 프로그래밍과 웹서비스 (2)
크로스 플랫폼(Cross Platform) (1)
임베디드 프로그래밍 (108)
멀티미디어 프로그래밍 (2)
스마트 TV(Smart TV) (14)
스마트 카(Smart Car) (27)
스마트 카 앱스토어 (0)
3D 프린터(3D Printer) (4)
네트워크 프로그래밍 (3)
웹 프로그래밍 (14)
해킹과 보안에관련된 프로그.. (221)
시스템 프로그래밍 (2)
데이타베이스 프로그래밍 (71)
인공지능 프로그래밍 (3)
로봇 프로그래밍 (3)
마이크로소프트 로보틱스 스.. (7)
로보코드(Robocode) (2)
무선 인터넷 프로그래밍 (0)
엑세스 기술 (698)

Total : 1,790,512
Today : 40 Yesterday : 237