Share to: share facebook share twitter share wa share telegram print page
Available for Advertising

JSON

JavaScript Object Notation, JSON (wym. [ˈeɪsən]) – lekki format wymiany danych komputerowych. JSON jest formatem tekstowym, bazującym na podzbiorze języka JavaScript. Typ MIME dla formatu JSON to application/json[1]. Format został opisany w dokumentach RFC 4627 ↓, ISO/IEC 21778:2017[2] oraz ECMA-404[3].

Pomimo nazwy, JSON jest formatem niezależnym od konkretnego języka. Wiele języków programowania obsługuje ten format danych przez dodatkowe pakiety bądź biblioteki. Wśród nich są ActionScript, C, C++, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, R, REBOL oraz Ruby.

Wykorzystanie

JSON jest jednym z nieformalnych sposobów przekazywania danych do aplikacji opartych na AJAX. W typowych przypadkach dane w formacie JSON są pobierane z serwera jako tekst przy wykorzystaniu obiektu XMLHttpRequest języka JavaScript, a następnie przekształcane w obiekt. Tekst powinien być kodowany za pomocą UTF-8, który jest w JSON domyślny.

 var http_request = new XMLHttpRequest();
 var url = "http://serwer.pl/to/jest/tylko/test"; // adres z danymi w formacie JSON

 // pobierz dane w formacie JSON z serwera
 http_request.onreadystatechange = handle_json;
 http_request.open("GET", url);
 http_request.send(null);

 function handle_json() {
        if (http_request.readyState == 4) {
                if (http_request.status == 200) {
                        var json_data = http_request.responseText; // pobranie tekstu
                        var the_object = JSON.parse(json_data); // zamiana tekstu na obiekt JSON
                } else {
                        alert('Wystąpił problem z wybranym adresem URL.');
                }
                http_request = null;
        }
 }

Powyższy kod jest znacząco uproszczony. Wykorzystany w tym przykładzie obiekt XMLHttpRequest nie jest dostępny we wszystkich przeglądarkach. W normalnych warunkach używa się dodatkowych funkcji lub metod przejściowych.

Krótki opis składni

Komunikat JSON jest literałem obiektu języka Javascript, który w tym języku jest tablicą asocjacyjną. Wszystkie dane są zmiennymi (nie stanowią kodu wykonywalnego), a nazwy składników (właściwości) obiektów są otoczone cudzysłowami. Wartości mogą być typu string (napis otoczony cudzysłowem), number (liczba typu double), stanowić jedną ze stałych: false null true, być tablicą złożoną z takich elementów lub obiektem. Obiekty i tablice mogą być dowolnie zagnieżdżane. Cały komunikat jest kodowany w unikodzie i domyślnie jest to UTF-8.

Przykład

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {"value": "New", "onclick": "CreateNewDoc()"},
        {"value": "Open", "onclick": "OpenDoc()"},
        {"value": "Close", "onclick": "CloseDoc()"}
      ]
    }
  }
}

Powyższe dane zapisane w YAML-u:

menu:
  id: file
  popup:
    menuitem:
    - onclick: CreateNewDoc()
      value: New
    - onclick: OpenDoc()
      value: Open
    - onclick: CloseDoc()
      value: Close
  value: File


Powyższe dane zapisane w XML-u:

 <menu id="file" value="File">
   <popup>
     <menuitem value="New" onclick="CreateNewDoc()" />
     <menuitem value="Open" onclick="OpenDoc()" />
     <menuitem value="Close" onclick="CloseDoc()" />
   </popup>
 </menu>

Porównanie z XML-em i innymi językami znaczników

Dostęp do danych w formacie JSON jest bardziej naturalny z poziomu języka JavaScript niż dostęp do tych samych danych w formacie XML, ponieważ JSON stanowi składniowy podzbiór języka JavaScript. Wbrew podobieństwu w nazwie, nie jest już jednak tak naturalny dla Javy i wymaga stosowania specjalnych bibliotek.

XML był początkowo jedynym językiem w usługach sieciowych, a więc dominującym przy sformalizowanej wymianie danych. Jednak w nowszych wersjach standardów dopuszczana jest także wymiana danych za pomocą JSON-a (np. w REST).

XML może być łatwiejszy przy czytaniu dowolnego fragmentu dokumentu – ze względu na nazwę znacznika widoczną także w końcowym znaczniku. Jednak z tego samego względu XML w praktyce zajmuje znacząco więcej miejsca niż analogiczny obiekt przesyłany za pomocą formatu JSON. Ilość przesyłanych danych jest z kolei szczególnie istotna w związku z dużą popularnością urządzeń mobilnych (w szczególności smartfonów).

YAML jest również językiem serializacji danych i stanowi nadzbiór języka JSON. JSON jest od niego jednak łatwiejszy do analizowania składni[4].

JSON.parse i bezpieczeństwo danych w przeglądarkach

Analiza składniowa (ang. parsing) danych w formacie JSON w JavaScript jest możliwe poprzez funkcję JSON.parse() lub eval(). Bezpieczniejsza jest jednak funkcja JSON.parse(). Zagrożenie polega na tym, że funkcja eval() powoduje wykonanie dowolnego kodu, czyli także takiego, który może być dowolnym poleceniem JavaScript, także złośliwym. Funkcja JSON.parse() nie jest na to wrażliwa, ponieważ sprawdza, czy analizowany ciąg znaków jest prawidłowy i tylko wtedy przekształca go na obiekt danych.

Należy zwrócić przy tym uwagę, że funkcja JSON.parse() wprowadzona została dopiero wraz z piątą wersją standardu ECMAScript i jest niedostępna w niektórych, starszych przeglądarkach internetowych[5]. Dla takich przeglądarek jak np. Internet Explorer 7 oraz 6 można jednak użyć zastępników[6].

Zobacz też

Przypisy

  1. The application/json Media Type for JavaScript Object Notation (JSON). datatracker.ietf.org, 2006-06. [dostęp 2022-06-02]. (ang.).
  2. ISO - ISO/IEC 21778:2017 - Information technology — The JSON data interchange syntax. iso.org, 2017-11. [dostęp 2022-06-02]. (ang.).
  3. ECMA-404. ecma-international.org, 2017-12. [dostęp 2022-06-02]. (ang.).
  4. Bob Ippolito: What happened to YAML?. 2005-07-19. (ang.).
  5. Can I use Json parsing. Can I use. (ang.).
  6. Douglas Crockford: JSON in JavaScript. (ang.).

Linki zewnętrzne

Read other articles:

2000 studio album by Suicidal TendenciesFree Your Soul...and Save My MindStudio album by Suicidal TendenciesReleasedSeptember 15, 2000RecordedTitan StudiosStall #2, Redondo Beach, California, U.S.GenreHardcore punkLength56:26LabelSuicidal RecordsProducerSuicidal TendenciesSuicidal Tendencies chronology Freedumb(1999) Free Your Soul...and Save My Mind(2000) Friends & Family, Vol. 2(2001) Free Your Soul...and Save My Mind is the tenth studio album by crossover thrash band Suicidal T...

هذه المقالة بحاجة لصندوق معلومات. فضلًا ساعد في تحسين هذه المقالة بإضافة صندوق معلومات مخصص إليها.   هذه المقالة عن السيفون. لمعانٍ أخرى، طالع مثعب (توضيح). مبدأ العمل المَثْعَب[1][2][3][4] أو السحارة[1] أو السيفون[1] (باليونانية: σίφων)‏ - وتعني باليون

  Bornéu britânico.  Bornéu neerlandês. Bornéu britânico foi composto pelas quatro partes do norte da ilha de Bornéu que atualmente correspondem ao Brunei, Labuão, Sabá e Sarauaque.[1][2] Durante o domínio colonial britânico até 1963, Sarauaque, Labuão e Sabá foram conhecidos como: Reino de Sarauaque (1841-1946) - Colônia da Coroa de Sarauaque (1946-1963) (atual Sarauaque), Colônia da Coroa de Labuão (1848-1946) (atual Labuão) e Bornéu do Norte (1881-194...

AbonAsalNegara asalIndonesia RincianJenishidangan lbs Abon sapi Abon (Bali: ᬳᬩᭀᬦ᭄; Jawa: ꦲꦧꦺꦴꦤ꧀; Sunda: ᮠᮘᮧᮔ᮪) adalah makanan tradisional Indonesia khas pulau Bali dan Jawa yang terbuat dari serat daging hewan. Penampilannya biasanya berwarna cokelat terang hingga kehitam-hitaman dikarenakan dibumbui gula jawa. Abon tampak seperti serat-serat kapas, karena didominasi oleh serat-serat otot yang mengering yang disuwir-suwir. Karena kering dan nyaris t...

Dwight L. Moody Dwight Lyman Moody adalah tokoh kebangunan rohani gelombang ketiga di Amerika Serikat, pada abad ke-19.[1] Ia juga dikenal sebagai pengkhotbah ulung yang sering mengadakan kebangunan rohani.[1] Moody lahir pada tanggal 5 Februari 1837 di Nothfield, Massachusetts dari keluarga petani miskin.[2] Ia dibaptis di Gereja Unitarian di desanya.[1] Pada tahun 1841, ayahnya meninggal.[2] Pada umur 17 tahun, ia pindah ke Boston untuk mencari pekerj...

1998 American filmSomewhere in the CityDirected byRamin NiamiWritten byPatrick DillonRamin NiamiProduced byRamin NiamiKaren RobsonStarringSandra BernhardOrnella MutiRobert John BurkePeter StormareBai LingCinematographyIgor SunaraEdited byElizabeth GazzaraRamin NiamiMusic byJohn CaleRelease date18 September 1998Running time94 min.CountryUnited StatesLanguageEnglish Somewhere in the City is a 1998 American indie comedy-drama film written and directed by Ramin Niami.[1][2] Cast S...

Jenny Frankhauser (2019) ChartplatzierungenErklärung der Daten Singles[1] Die Zeit steht still   DE 64 12.08.2016 (1 Wo.) Jennifer „Jenny“ Eileen[2] Frankhauser (* 25. August 1992 in Ludwigshafen am Rhein) ist eine deutsche Reality-TV-Teilnehmerin und Sängerin. Inhaltsverzeichnis 1 Leben 2 Fernsehsendungen 3 Diskografie 4 Weblinks 5 Einzelnachweise Leben Jenny Frankhauser wuchs mit ihrem Halbbruder und ihrer Halbschwester Daniela Katzenberger als Tochter von Ir...

Villa Meeresgruss (Sea Greeting) in Binz, Rugia Island - a typical mansion in German resort architecture style Resort architecture[1] (German: Bäderarchitektur) is an architectural style that is especially characteristic of spas and seaside resorts on the German Baltic coast. The style evolved since the foundation of Heiligendamm in 1793, and flourished especially around the year 1870, when resorts were connected to big cities via railway lines. Until today, many buildings on the Ger...

Play by George Bernard Shaw Notice for the first production, 1905 Passion, Poison, and Petrifaction is a short play by Bernard Shaw, subtitled The Fatal Gazogene: a Brief Tragedy for Barns and Booths. It is a comic mock-melodrama, written to raise funds for charity. It has been revived occasionally, in tandem with other short works by Shaw or by other playwrights. Background Shaw began writing the play in May 1905 and finished it on 4 June. It was published in Harry Furniss's Christmas Annual...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (نوفمبر 2019) ريجنالد جادسون   معلومات شخصية الميلاد 29 سبتمبر 1881[1]  الوفاة 26 أغسطس 1972 (90 سنة)   أوكلاند  مواطنة نيوزيلندا  الحياة العملية المهنة عسكري  ا...

Disused railway station in Jedburgh, Scottish Borders JedfootThe site of the station, looking north towards Roxburgh, in 2000General informationLocationJedburgh, Scottish BordersScotlandCoordinates55°30′34″N 2°32′18″W / 55.5095°N 2.5383°W / 55.5095; -2.5383Grid referenceNT661241Platforms1Other informationStatusDisusedHistoryOriginal companyJedburgh Railway CompanyPre-groupingNorth British RailwayPost-groupingLNER British Railways (Scottish Region)Key dates1...

Skyscraper office complex in Xinyi District of Taipei, Taiwan CTBC Financial Park 中國信託金融園區General informationStatusCompletedTypeOfficeLocationNo. 168, Jingmao 2nd Road, Nangang District, Taipei, TaiwanCoordinates25°03′33″N 121°36′56″E / 25.059225851206413°N 121.61544451176596°E / 25.059225851206413; 121.61544451176596Construction started2010Completed2013HeightArchitecturalBlock A: 139 m (456 ft) Block B: 99.4 m (326 ft) B...

Railway station in the 9th arrondissement of Lyon, France You can help expand this article with text translated from the corresponding article in French. (March 2019) Click [show] for important translation instructions. View a machine-translated version of the French article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy...

Satellite constellation providing internet connectivity This article is about satellites in Low Earth orbit only. For internet provision by satellites in other orbits, see Satellite constellation and Satellite internet access. A satellite internet constellation is a constellation of artificial satellites providing satellite internet service. In particular, the term has come to refer to a new generation of very large constellations (sometimes referred to as megaconstellations[1]) orbit...

Greek award show presented by the MAD TV Mad Video Music AwardsMad Video Music Awards 2020 logoCountryGreecePresented by MAD TV (2004–present) ANT1 (2004–2005, 2012–2014) Alpha TV (2006–2011, 2015–2019) Mega Channel (2020–present) First awarded2004-presentWebsiteOfficial website The MAD Video Music Awards is a Greek award show presented by the MAD TV. The awards honor the year's biggest achievements in music, voted by the viewers of Mad television. Winners receive an authentic Mad...

Belgische graven en één Brits graf uit WO1 De Belgische militaire begraafplaats van Brugge is een militaire begraafplaats aan de Kleine Kerkhofstraat in de Belgische stad Brugge. De begraafplaats is een onderdeel van de Centrale Stedelijke Begraafplaats in de Brugse deelgemeente Assebroek. De militaire begraafplaats heeft een oppervlakte van 50 are waarop 611 militairen liggen. Daarvan zijn er 522 Belgen en 1 Brit uit de Eerste Wereldoorlog. De meesten zijn omgekomen tijdens het bevrijdings...

1971 pornographic film For other uses, see Geek (disambiguation). The GeekDVD released by Something Weird VideoStarringLynn HolmesNora WieternikRic LutzeProductioncompanyBrutus ProductionsDistributed byBrutus ProductionsRelease dates July 7, 1971 (1971-07-07) (San Francisco, California) Running time56 minutesCountryUnited StatesLanguageEnglish The Geek is a pornographic film released in 1971. It is about a group of adults hiking and camping, that are eventually ambushed by ...

Đặng Văn MinhChức vụChủ tịch Ủy ban nhân dân tỉnh Quảng NgãiNhiệm kỳ15 tháng 9 năm 2020 – nay3 năm, 84 ngàyTiền nhiệmTrần Ngọc CăngKế nhiệmđương nhiệmPhó Chủ tịchNguyễn Tăng Bính (12/2017-10/2020)Đặng Ngọc Dũng (6/2016-11/2020)Võ Phiên (4/2019-)Trần Phước Hiền (12/2020-) Phó Bí thư Tỉnh ủy Quảng NgãiNhiệm kỳ11 tháng 9 năm 2020 – nay3 năm, 88 ngày Thông ...

Nominal head of a Nepalese province appointed by the President of Nepal Governor of Provinces of Nepalप्रदेश प्रमुखFlag of NepalStyleThe HonourableResidenceVariousAppointerPresident of NepalTerm length5 yearsFormation2019Salary76,240 Nepalese rupees (NPR)[1] Politics of Nepal Constitution Fundamental Rights and Duties Human rights LGBT rights Government President: Ram Chandra Poudel Vice President: Ram Sahay Yadav Executive: Prime Minister (list): Pushpa Kamal ...

若非特別註明,本條目所有時間皆為東八區標準時間(UTC+8)。 臺鐵臺北車站刺警案位置 中華民國臺灣鐵路管理局臺北車站日期2021年5月22日晚間5點20分[1][2](國家標準時間)類型持刀刺殺武器開山刀[1]受傷2人[3]動機拒絕被中華民國警察逮捕 2021年臺鐵臺北車站刺警案中華民國法院制度法院臺灣臺北地方法院判决下达日期2021年9月15日 (2021-09-15)...

Kembali kehalaman sebelumnya