) and between the servers themselves (HTTP software interfaces). JSON is also well suited for storing complex dynamic structures in relational databases or file caches.
Since the JSON format is a subset of the syntax JavaScript language then it can be quickly deserialized with the built-in eval () function. In addition, it is possible to insert fully functional JavaScript functions. In PHP 5.2.0 and later, JSON support is included in the core in the form of json_decode () and json_encode () functions, which themselves convert JSON data types to their corresponding PHP types and vice versa.
Syntax
JSON is built on two structures:
- A set of key / value pairs. In various languages this is implemented as an object, record, structure, dictionary, hash table, keyed list, or associative array. The key can only be a string, the value can be any form.
- A numbered set of values. In many languages this is implemented as array, vector, list or sequence.
These are generic data structures. In theory, everything modern languages programming support them in one form or another. Since JSON is used to exchange data between different programming languages, it makes sense to build it on these structures.
JSON uses the following forms:
- An object is an unordered set of name / value pairs enclosed in curly braces (). There is a symbol between the name and the meaning ": " and the name / value pairs are separated by commas.
- Array(one-dimensional) is a set of values that have ordinal numbers (indices). The array is contained in square brackets... The values are separated by commas.
- Meaning may be string in double quotes, number, value true or false, object, array, or the value null... These structures can be nested within each other.
- Line is an ordered set of zero or more Unicode characters, enclosed in double quotes, using backslash escape sequences. Characters are represented by a simple string.
- Name is a string.
Line very similar to string in languages and Java. Number is also very similar to a C or Java number, except that only decimal format is used. Spaces can be inserted between any two characters.
The following example shows the JSON representation of an object describing a person. The object has string first and last name fields, an object describing the address, and an array containing a list of phone numbers.
("firstName": "Ivan", "lastName": "Ivanov", "address": ("streetAddress": "Moskovskoe sh., 101, apt. 101", "city": "Leningrad", "postalCode": 101101), "phoneNumbers": ["812 123-1234", "916 123-4567"])
In XML language, such a structure would look something like this:
Comparison with YAML
Both functionally and syntactically, JSON is a subset of the YAML language. In particular, the YAML 1.2 specification states that "any JSON file is a valid YAML file." The most common YAML parser is capable of handling JSON as well. The YAML spec prior to version 1.2 did not fully cover JSON, primarily due to the lack of native UTF-32 support in YAML, and the requirement for a space after the comma separator. In addition, the JSON specification included / * * / style comments.
The most important YAML difference is a set of syntax extensions that have no counterpart in JSON:
Relational: YAML supports relational data: in a YAML document, you can refer to an anchor previously encountered in a file / stream. This is how recursive structures can be expressed. Extensible: YAML supports extensible data types besides primitives (i.e. strings, numbers, booleans). Blocks: Indented block syntax is available in YAML; it allows you to describe structured data without using extra characters (all kinds of brackets, quotes, etc.).
JSON Schema
JSON Schema is one of the languages for describing the structure of a JSON document. Uses JSON syntax. Based on the concepts of XML Schema, RelaxNG, Kwalify. JSON Schema is a self-describing language: when used to process data and describe its validity, the same serialization / deserialization tools can be used.
Using JSON in Ajax
The following Javascript code example shows how the browser can use XMLHttpRequest to request a JSON object from the server (the server side of the program is omitted; it must contain the code that sends data in the JSON string format in response to url requests).
Var the_object; var http_request = new XMLHttpRequest (); http_request.open ("GET", url, true); http_request.send (null); http_request.onreadystatechange = function () (if (http_request.readyState == 4) (if (http_request.status == 200) (the_object = JSON.parse (http_request.responseText);) else (alert ( "There was a problem with the URL."); ) http_request = null; ));
notice, that given example XMLHttpRequest is not universal for all browsers (for browsers based on Internet Explorer, Opera, Safari, and Mozilla, there must be some differences in the code). XMLHttpRequest is limited by the same origin policy: the response URL must be in the same DNS domain as the server hosting the page requesting the response. Alternatively, a JSONP approach is taken that involves using a coded function call between the client and the server so that the client can load JSON-encoded data from third-party domains and notify the caller of completion, although this introduces some security risks and additional server requirements.
Alternatively, in the page code, you can use the elements
You can also use the same origin policy rule to pass JSON data with dynamic tags, but it results in vulnerable code. JSONRequest has been suggested as a safer alternative.
Security questions
Although JSON is designed to be serialized, its syntax follows JavaScript and poses a number of security concerns. Often to process data received from external source in JSON format, the eval () function is applied to them without any prior validation.
JavaScript eval ()
Since JSON appears to be a syntactically correct piece of JavaScript code, the simplest way to parse JSON data in a JavaScript program is to use the builtin in JavaScript functions eval (), which is used to execute JavaScript expressions. This approach eliminates the need for additional parsers.
The eval () technique makes the system vulnerable if the source of the used JSON data is not trusted ( English). Such data can be malicious JavaScript code for attacks of the Code Injection class ( English). With the help of this vulnerability, it is possible to steal data, fake authentication. However, the vulnerability can be eliminated by using additional data validation tools. For example, before eval () is executed, data received from an external source can be validated using regular expressions. The RFC defining JSON suggests using the following code to validate it conforms to the JSON format
Var my_JSON_object =! ( / [^,:()\ [\\\0-9.\-+Eaeflnr-u \ n \ r \ t] /.test (text.replace (/"(\\.|†^"\\\)*"/g, ""))) && eval ("(" + text + ")");
As a safer alternative to eval () has been suggested new function parseJSON (), which can only process JSON data. It was introduced in the fourth version of the ECMAScript standard and is described in the article "JSON: A Lightweight Alternative to XML". It is currently available as a JavaScript library and will be included in ECMAScript 5th Edition.
Inline JSON
Recent versions of web browsers have built-in support for JSON and are capable of handling it without calling the eval () function, which leads to the described problem. JSON processing is usually faster in this case. So in June 2009 the following browsers had built-in JSON support:
At least five popular JavaScript libraries use inline JSON when available:
Cross-domain request forgery
Rough use of JSON makes sites vulnerable to Cross Site Request Forgery (CSRF or XSRF). Since the tag to access servers other than the server from which the page was loaded.
Without using JSONP technology (that is, using just JSON data encoding), the server can return only data. For example like this:
("paper": "A4", "count": 5)
However, this is only data and cannot affect the browser.
Using the JSONP technique, the name of the callback function is passed to the third-party server in the call (GET) string:
Here the jsonp parameter contains the callback name of the parseResponse function.
Now the third-party server example.com can return the following code:
ParseResponse (("paper": "A4", "count": 5))
The code now calls the first domain's javascript function.
The idea was originally proposed on the MacPython blog in 2005 and is currently used by many Web 2.0 applications such as Dojo Toolkit Applications, Google Toolkit Applications, and zanox Web Services. Further extensions to this protocol have been proposed with additional arguments introduced, such as in the case of JSONPP with support for S3DB web services.
Since JSONP uses script tags, the calls are essentially open to the world. For this reason, JSONP may be inappropriate for storing sensitive data.
Including script tags from remote sites allows them to transfer any content on the site. If the remote site has vulnerabilities that allow Javascript injections, then the original site can also be affected by them.
JSONPP(parameterized JSON with padding) Parameterized JSON with padding - development of the JSONP idea
JSONPP includes the URL of the source, the name of the function that will process the JSON data, a string for eval after receiving the data, and a string for eval after finishing processing the data:
JSON_call (SRC, JSONP, JSONPP, ONLOAD);
eventually turns around
Ans = JSONP (SRC) (eval (JSONPP (ans)); eval (ONLOAD);)
In general, for the very idea of JSONPP, the number of parameters is not important. SRC, JSONP, JSONPP are enough (and their server-side and then client-side processing) for it to be JSONPP.
Let's look at an example of working with the S3DB service.
Function s3db_jsonpp_call (src, next_eval) (var call = "call_" + Math .random () .toString () .replace (/\./g, ""); var headID = document.getElementsByTagName ("head") [0 ]; var script = document.createElement ("script"); script.id = call; script.type = "text / javascript"; // using padded, parameterized json src = src + "& format = json & jsonp = s3db_jsonpp & jsonpp ="+ next_eval + "& onload = remove_element_by_id (" "+ script.id + "") "; script.src = src; headID.appendChild (script); // retrieve answer) function s3db_jsonpp (ans, jsonpp) (eval (jsonpp); return ans;) function remove_element_by_id (id) (var e = document.getElementById (id); e.parentNode .removeChild (e); return false;)
In the example, the s3db_jsonpp_call () function creates in the DOM head a script element whose src corresponds to a JSONPP call.
After receiving a response from the server, s3db_jsonpp () will be called - it is passed in the call parameters, as it should be according to the JSONP rules.
Inside s3db_jsonpp (), eval (jsonpp) will be triggered and the value ans will be returned.
The call to eval (onload) leads to the execution of remove_element_by_id () with the id of the created script in the head and eventually to its removal, because it will not be used anyway, since the id in the example was generated randomly at the very beginning of the s3db_jsonpp_call () function. This call is in response from the server.
Object references
The JSON standard does not support object references, however, the Dojo Toolkit demonstrates how additional conventions can support such references using standard JSON. In particular, the dojox.json.ref module provides support for several forms of links, including circular, plural, cross-document, and lazy links.
see also
Notes (edit)
- YAML Ain't Markup Language (YAML ™) Version 1.2 (English). - Working Draft 2008-05-11. (unavailable link - history) Retrieved September 24, 2009.
- ... RedHanded 07 Apr 2005. Retrieved September 25, 2012..
- Json.Com JSON Schema Proposal. (unavailable link - history)
- RFC 4627
- JSON: A fat-free alternative to XML. Archived
- json2.js. Archived from the original on February 12, 2012. Retrieved September 24, 2009.
- Using inline JSON.
- IE8 Embedded JSON. Archived from the original on February 12, 2012.
- Web Specifications Supported in Opera Presto 2.5 (March 10, 2010). Archived from the original on February 12, 2012. Retrieved March 29, 2010.
- ES 3.1 implementation of the JSON object.
- Ticket # 4429lang = en. Archived from the original on February 12, 2012.
- Ticket # 4429 (May 22, 2009). Archived from the original on February 12, 2012. Retrieved July 3, 2009.
- Ticket # 8111lang = en. Archived from the original on February 12, 2012.
- MooTools Core & More 1.3.1. Archived from the original on February 12, 2012.
- YUI 2: JSON utility (September 1, 2009). Archived from the original on February 12, 2012. Retrieved October 22, 2009.
- Learn JSON (April 7, 2010). Archived from the original on February 12, 2012. Retrieved April 7, 2010.
- Jeremy Grossman Advanced attack techniques for web applications using GMail. WhiteHat Security. Archived from the original on February 12, 2012. Retrieved September 23, 2009.
- from __future__ import * "Remote JSON - JSONP. Bob.pythonmac.org. Archived from the original on February 12, 2012. Retrieved September 8, 2008.
- Almeida, Jonas (June 11, 2008). “JSON, JSONP, JSONPP? "(S3DB). Retrieved 2009-04-26.
- RIAspot JSON P for Cross Site XHR. (unavailable link - history)
- JSON referencing in Dojo. Archived from the original on February 12, 2012.
Links
- Official format homepage in Russian
- json.js, json2.js is a library developed by Douglas Crockford for working with JSON data in JavaScript. Extends an Object using the toJSONString method, which is then present in any object, and converts it to a JSON string.
- json-rpc.org
Document markup languages | |
---|---|
Office documents | Compound Document Format OOXML (SpreadsheetML, PresentationML, WordprocessingML) |
A lesson that looks at what JSON is and how it has advantages over other data formats.
JSON concept
JSON (JavaScript Object Notation) is a textual format for representing data in JavaScript object notation.
This means that the data in JSON is organized just like it is in a JavaScript object. But unlike the latter, the JSON recording format has some peculiarities, which will be discussed a little later.
JSON is usually used in conjunction with AJAX so that the server can transmit data in a convenient form to JavaScript, which will then display it on the page.
JSON format structure
Anyone familiar with the process of creating objects in JavaScript will not see anything new in the structure of the JSON format. This is because the JSON structure matches the JavaScript object structure with some restrictions.
It's easier to think of JSON as a container of elements. Each element in such a container is a structural unit consisting of a key and a value.
In this case, the value is directly related to the key and form a so-called key-value pair. In order to get the value in such an object, you need to know its key. Syntactically, such data in JSON is written as follows:
In the above entry, you can see that the key is separated from the value using a colon (:). In this case, the key in the JSON object must be enclosed in double quotes. This is the first feature of JSON that differentiates it from a JavaScript object. Because in a JavaScript object, the key (property of the object) does not have to be enclosed in double quotes.
For example, an object structure that is valid from a JavaScript point of view and not valid from a JSON point of view:
Var person = (name: "Ivan";) // JavaScript object
Warning: try to set the name of the key so as not to complicate access to the data, i.e. it is preferable to use camel notation when composing the name, or use an underscore ("_") to connect words.
The key value in JSON can be written in one of the following formats: string (string), number (number), object (object), array (array), boolean ( boolean value true or false), null (a special JavaScript value).
it the second limitation is in JSON, since JavaScript object can contain any data type, including a function.
Var person = ("name": "Ivan"; "setName": function () (console.log (this.name);)) // JavaScript object
To separate one element (key-value pair) from another, use the comma sign (,).
For example, consider JSON consisting of different types data.
Note: The JSON data format does not allow comments inside its structure.
Working with JSON in JavaScript
Unlike a JavaScript object, JSON is a string.
For example:
// for example the variable personData contains a string that is JSON var personData = "(" name ":" Ivan "," age ": 37," mother ":(" name ":" Olga "," age ": 58), "children": ["Masha", "Igor", "Tanya"], "married": true, "dog": null) ";
Working with JSON is usually done in two ways:
- Parsing is translating a string containing JSON into a JavaScript object.
- Convert JavaScript object to JSON string. In other words, this action performs the opposite of parsing.
Parsing JSON
Parsing JSON, i.e. translating a JSON string into a JavaScript object is done using the eval () or parse () method.
Using the eval () method:
// the person variable is a JavaScript object that is obtained by executing JSON code (string) var person = eval ("(" + personData + ")");
Using JSON.parse () method:
// the variable person is a JavaScript object that is obtained by parsing a JSON string var person = JSON.parse (personData);
Converting JavaScript object to JSON string
Translating a JavaScript object into a JSON string is done using the JSON.stringify () method. This method performs the opposite of the JSON.parse () method.
Var personString = JSON.strigify (person);
Benefits of the JSON format
The JSON data format has the following advantages:
- convenient and quick-to-use methods for converting (parsing) a JSON string into a JavaScript object and vice versa;
- clear and simple data structure;
- very small size compared to other data formats (eg XML). This is because the JSON format contains the least possible formatting, i.e. only a few special characters are used in its writing. This is a very important advantage because data presented in JSON format will load faster than if it were presented in other formats.
Due to the fact that this format has so many advantages, it began to be used not only in JavaScript, but also in many other languages, such as C, Ruby, Perl, Python, PHP, etc.
Comparison of JSON and XML formats
JSON has the following advantages over XML:
- For some data, the JSON size will be significantly smaller than the XML size when transferring some data.
- JSON has more convenient methods for converting to structures JavaScript data than XML.
- JSON is easier to create than XML.
The post-parsed JSON data is handled like a JavaScript object.
// JSON var personData = "(" name ":" Ivan "," age ": 37," mother ":(" name ":" Olga "," age ": 58)," children ": [" Masha " , "Igor", "Tanya"], "married": true, "dog": null) "; // JavaScript object person var person = JSON.parse (personData);
Let's consider the main points:
// get the values of the key (property) name person.name; person ["name"]; // get the values of the key (property) name located in the mother object person.mother.name; // delete the age element delete (person.age) // add (or update) the key (property) person.eye = "brown"; // when working with arrays, you must use methods designed to work specifically with arrays // remove 1 element from the array (splice method) person.children.splice (1,1) // add an element to the array (push method) person.children. push ("Katya");
To iterate over the elements in an object, you can use the for..in loop:
For (key in person) (if (person.hasOwnProperty (key)) (// key = key // value = person console.log ("Key =" + key); console.log ("Value =" + person) ;) // if the person object has a key (if person has a key property)) // iterate over all the keys (properties) in the object
To iterate over the elements of an array, you can use the following loop:
For (var i = 0; i
JSON (JavaScript Object Notation) is a data transfer format. As the name suggests, the format is based on the language JavaScript programming however it is available in other languages as well (Python, Ruby, PHP, Java).
JSON uses the .json extension. When used in other file formats (such as .html), the JSON string is quoted or assigned to a variable. This format is easily transferred between the web server and the client or browser.
Lightweight and easy to read, JSON is a great alternative to XML.
This tutorial will walk you through the benefits, objects, general structure, and syntax of JSON.
JSON syntax and structure
A JSON object is in the form of key / value and is usually written within curly braces. When working with JSON, all objects are stored in a .json file, but they can also exist as separate objects in the context of a program.
The JSON object looks like this:
"first_name": "John",
"last_name": "Smith",
"location": "London",
"online": true,
"followers": 987
This is a very simple example. A JSON object can contain many strings.
As you can see, the object is made up of key-value pairs that are enclosed in curly braces. Most of the data in JSON is written as objects.
A colon is placed between the key and the value. Each pair must be followed by a comma. The result is:
"key": "value", "key": "value", "key": "value"
The JSON key is on the left. The key must be enclosed in double quotes. Any valid string can be used as a key. Within one object, all keys must be unique. The key can contain a space ("first name"), but programming problems can arise with access to such a key. Therefore, instead of a space, it is better to use an underscore ("first_name").
JSON values are on the right side of the column. Any simple data type can be used as a value:
- Strings
- Numbers
- Objects
- Arrays
- Boolean data (true or false)
Values can also be represented by complex data types (for example, objects or JSON arrays).
JSON supports individual syntax for each of the above data types: if the value is a string, then it will be quoted, and if it is a number, then it will not.
Typically, data in .json files is written to a column, however JSON can be written to a string as well:
("first_name": "John", "last_name": "Smith", "online": true,)
This is how JSON data is usually written to other file types.
By writing JSON data to a column, you improve the readability of the file (especially if there is a lot of data in the file). JSON ignores whitespace between columns, so you can use them to split your data into a human-readable number of columns.
"first_name": "John",
"last_name": "Smith",
"online": true
Please note: JSON objects are very similar to JavaScript objects but they are not the same format. For example, JavaScript can use functions, but JSON cannot.
The main advantage of JSON is that data in this format is supported by many popular programming languages, so it can be quickly transferred.
You are now familiar with the basic JSON syntax. But JSON files can have a complex, hierarchical structure that includes nested arrays and objects.
Complex types in JSON
JSON can store nested objects and arrays, which will be passed as the value of the key assigned to them.
Nested objects
Below you will find an example - the users.json file, which contains data about users. For each user
("John", "jesse", "drew", "jamie") a nested object is passed as a value, which, in turn, also consists of keys and values.
Note: The first nested JSON object is highlighted in red.
"john": (
"username": "John",
"location": "London",
"online": true,
"followers": 987
"jesse" :(
"username": "Jesse",
"location": "Washington",
"online": false,
"followers": 432
"drew": (
"username": "Drew",
"location": "Paris",
"online": false,
"followers": 321
"jamie": (
"username": "Jamie",
"location": "Berlin",
"online": true,
"followers": 654
Note that curly braces are used in both the nested and the main object. Commas are used in nested objects in the same way as in regular ones.
Nested arrays
Data can be embedded in JSON using JavaScript arrays to be passed as values. JavaScript uses square brackets () at the beginning and end of an array. An array is an ordered collection of data that can contain data of various types.
An array is used to transfer a large amount of data that can be grouped. For example, let's try to record user data.
{
"first_name": "John",
"last_name": "Smith",
"location": "London",
"websites": [
"description": "work",
"URL": "https://www.johnsmithsite.com/"
},
{
"desciption": "tutorials",
"URL": "https://www.johnsmithsite.com/tutorials"
"social_media": [
"description": "twitter",
"link": "https://twitter.com/johnsmith"
"description": "facebook",
"link": "https://www.facebook.com/johnsmith"
"description": "github",
"link": "https://github.com/johnsmith"
The keys "websites" and "social_media" are assigned arrays as values, which are placed in square brackets.
Using nested arrays and objects, you can create complex data hierarchies.
JSON or XML?
XML (eXtensible Markup Language) allows you to store data in a form that is convenient for human and machine perception. The XML format is supported by a wide variety of programming languages.
XML and JSON have a lot in common. However, XML requires a lot more text, therefore, such files are larger and more difficult to read and write. Moreover, XML can only be processed using an XML interpreter, while JSON can be processed using a simple function. Unlike JSON, XML cannot store arrays.
Let's compare two files: they contain the same data, but the first is written in XML format and the second in JSON.
users.xml
users.json
("users": [
("username": "John", "location": "London"),
("username": "Jesse", "location": "Washington"),
("username": "Drew", "location": "Paris"),
("username": "JamieMantisShrimp", "location": "Berlin")
JSON is a very compact format and does not require as many tags as XML. Also, XML, unlike JSON, does not support arrays.
If you are familiar with HTML, you will notice that XML format very similar to it (in particular with tags). JSON is simpler, requires less text, and is easier to use, for example, in AJAX applications.
Of course, the format should be chosen depending on the needs of the application.
Tools for JSON
JSON is commonly used in JavaScript, however, this format is widely used in other programming languages.
More information on JSON compatibility and handling can be found on the project site and in the jQuery library.
Writing JSON from scratch is rare. Typically, data is loaded from sources or converted to JSON. You can convert CSV or tab-delimited data to JSON using the open tool Mr. Data Converter. To convert XML to JSON and vice versa, use utilities-online.info. When working with automatic tools, be sure to check the result.
JSON files (including converted data) can be checked using the JSONLint service. To test JSON in a web development context, refer to the JSFiddle.
Conclusion
JSON is a simple and lightweight data format. JSON files are easy to transfer, store, and use.
JSON is used a lot in APIs today.
Attribute-value pairs. It is the most common data format used for asynchronous communication between browser and server, largely replacing XML (used by AJAX).
JSON is a language independent data format that was derived from JavaScript. Since 2017, many programming languages use code to generate and analyze data in only it. JSON file names use the .json extension.
History of creation
The JSON format was originally developed by Douglas Crockford in the early 2000s, and subsequently two competing standards (RFC 7159 and ECMA-404) defined it in 2013. The ECMA standard only describes valid syntax, while the RFC covers some of the basics of security and interoperability.
In addition, there is RFC 7493, which defines a restricted profile known as I-JSON (short for Internet JSON). He seeks to overcome some communication problems. Each such document is a valid JSON document.
The need to create this format grew out of the need for a real communication protocol between the server and the browser, carried out in real time without the use of plugins (such as Flash or Java applets).
Development and application
As noted, Douglas Crockford, the creator of StateSoftware, pioneered and popularized the JSON format. Subsequently, the co-founders agreed to build a system using standard browser capabilities and provided an abstraction layer for developers to create applications with a continuous duplex connection to a web server. At the same time, it became possible to keep two HTTP connections open and process them until the standard operating time of the browser, if no data exchange was performed. The co-founders held a roundtable discussion and voted to name the data format JSML or JSON, and determine the type of license under which new development will become available. The format is currently open source.
Practical use
The JSON.org website was launched in 2002. In December 2005, Yahoo! started offering some of its web services in this format. Google only started using JSON feeds for its GData web protocol in December 2006.
The JSON file format was originally intended for a subset of the JavaScript scripting language (specifically Standard ECMA-262 3rd Edition-December) and was commonly used with it. However, this is a data language independent format. The code for parsing and generating JSON data is available in many programming languages. The JSON website lists all the libraries.
Although the online JSON format was initially advertised and considered a strict subset of JavaScript and ECMAScript, it occasionally allows some non-escaped characters in strings that are illegal in JavaScript strings and ECMAScript.
JSON itself became an international ECMA standard in 2013 as ECMA-404, which was used as a reference in RFC 7158 the same year. In 2014, RFC 7159 became the primary reference for the use of JSON on the web (e.g. MIME application / json).
Data types, syntax and example
The main JSON data types are:
- Number: A signed decimal number that can contain a fractional part and can use the exponential notation E, but cannot include non-numbers (such as NaN). The format makes no distinction between integers and floating point numbers. JavaScript uses double precision floating point format for all of its numeric values, but other languages that implement JSON may encode them differently.
- String: A sequence of zero or large Unicode characters. Strings are delimited by double quotation marks and support the backslash syntax.
- Literals: any of values true or false.
- Array: An ordered list of zero or more values, each of which can be of any type. Arrays use square brackets with commas.
- Object: An unordered collection of name / value pairs, where names (also called keys) are strings. Since objects are designed to represent associative arrays, it is recommended (although not required) that each key be unique within it. Objects are separated by curly braces and use commas to separate each pair, while inside each of them a colon character separates the key or name from its value.
- Null: An empty value using the word null.
Restricted spaces are allowed and can be placed around or between syntactic elements (meaning and punctuation, but not within the string value). For this purpose, only four special characters spaces are counted: space, horizontal tab, line feed, and forward slash. In particular, the byte order mark does not have to be generated by a conforming implementation (although it can be accepted when parsing JSON). The JSON request does not provide syntax for comments.
Earlier versions (such as those specified in RFC 4627) required that a valid document only consist of an object or array type, which could contain other types within them. This JSON format, an example of which can be found on legacy web pages, is currently not used.
Data portability issues
Although Douglas Crockford originally argued that JSON is a strict subset of JavaScript, its specification actually allows documents to be created that are unreadable in JavaScript. Specifically, JSON allows the Unicode string values U + 2028 LINE SEPARATOR and U + 2029 PARAGRAPH SEPARATOR to appear unescaped in quoted strings, but JavaScript does not. This is because JSON only prohibits "control characters". For maximum compatibility, these characters should be escaped with a backslash. This subtlety is important when creating JSONP.
JSON format: how to open it?
JSON documents can be encoded in UTF-8, UTF-16, or UTF-32, the default encoding is UTF-8. These standards support the full set of "Unicode" characters, including characters outside the main multilingual plane (U + 10000 to U + 10FFFF). However, if escaped, these characters must be written using UTF-16 surrogate pairs - a detail that some JSON parsers miss. How to open and how will such a file be read?
Numbers in this format are agnostic about their representation in programming languages. There is no difference between an integer and a floating point value: some implementations may treat 42, 42.0, and 4.2E + 1 as the same number, while others may not. In addition, there are no requirements for issues such as overflow, underflow, loss of precision, or rounding. Also, the JSON format says nothing about the handling of signed zeros, regardless of whether 0.0 is other than -0.0. Most implementations using the IEEE 754 floating point standard, including JavaScript, store signed zeros, but not all JSON implementations can.
Usage in JavaScript
Since the JSON format was derived from JavaScript and its syntax is (mostly) a subset of the language, you can use the JavaScripteval function to parse the JSON data. Due to the problem with parsing Unicode string terminators discussed in the previous section, the eval function must replace them.
It is unsafe if the string is not properly validated. Instead, you should use the JSON parser library or JavaScript support to read and write JSON.
A properly implemented parser only accepts valid JSON format, as described in the system, preventing the unintended execution of potentially malicious code.
Since 2010, web browsers such as Firefox and Internet Explorer support for parsing and exporting to JSON format is included.
Unsupported native data types
JavaScript syntax defines several native data types that are not included in the JSON standard: Map, Set, Date, Error, Regular Expression, Function, and a few others. These JavaScript data types must be represented in some other format, with both programs agreeing on how to convert between types. There are some defacto standards today, such as converting a date to a string, but none of them are generally accepted. Other languages may have a different set of native types that must be serialized carefully to deal with this type of conversion.
JSON schema
A schema is used to define a JSON data structure for validation, documentation, and interaction management. It provides a kind of contract for the data required by the application and a way to modify it.
The schema is based on concepts from XML Schema (XSD), but is proprietary. As with XSD, the same serialization / deserialization facilities are used for both schema and data.
Schema is an internet project that is currently in version 5 (released October 13, 2016). There are several validators available for different programming languages, each with a different level of compliance. There is no standard file extension, but some experts suggest approving .schema.json.
MIME type
The official MIME type for JSON text is "application / json". Although most modern implementations have adopted the official MIME type, many applications continue to provide legacy support for other MIME types. Many service providers, browsers, servers, web applications, libraries, frameworks and APIs use, expect, or recognize a MIME type whose content looks like "text / json" or "text / javascript". Notable examples include Google Search API, Yahoo !, Flickr, Facebook API, DojoToolkit 0.4, and so on.
JSON-RPC
JSON-RPC is a JSON-based remote procedure call (RPC) protocol created as a replacement for XML-RPC or SOAP. It is a simple protocol that only defines a few types of data and commands. It allows the system to send notifications (information to the server that does not require a response) and multiple calls to the server that can be answered out of order.
AJAJ
Asynchronous JavaScript and JSON (or AJAJ) refer to the same dynamic web page methodology as Ajax, but instead of XML, it is the JSON data format that dominates. AJAJ is a web development technology that enables a web page to request new data after being loaded into a browser. It usually displays them from the server in response to user actions on that page. For example, what the user types in the search box, the client code then sends to the server, which immediately responds with a drop-down list of matching database items.
Security concerns
JSON text is defined as a data serialization object. However, its design, as a loose subset of the JavaScript scripting language, poses several security concerns. They focus on using the Javascript interpreter to dynamically execute JSON text like inline JavaScript. This exposes the program to erroneous or malicious scripts. This is a serious problem when dealing with data retrieved from the Internet.
This simple and popular but risky method takes advantage of JavaScripteval compatibility.
Some developers mistakenly believe that JSON text is also syntactically similar to JavaScript, although this is only partially true. Therefore, it is believed that an easy way for a JavaScript program to parse data in this format is to use the built-in JavaScripteval function, which was designed to evaluate Javascript expressions. Instead of using a specific parser, the interpreter itself is thus used to execute JSON data, creating natural JavaScript objects. However, this method is risky if there is a possibility that the JSON data may contain arbitrary Javascript, which will then be executed in the same way. If no steps are taken to validate the data first, the eval method is vulnerable to security vulnerabilities where the data and the entire JavaScript environment are not under the control of a single trusted source.
For example, if the data is not validated, it is attacked by malicious JavaScript. Such violations can also pose the risk of data theft, authentication forgery, and other potential misuse of data and resources.
Thus, the new JSON.parse function has been designed as a safer alternative to eval. It is specifically designed to handle JSON data, not JavaScript. It was originally planned for inclusion in the fourth edition of the ECMAScript standard, but this did not happen. It was first added in version 5 and is now supported by major browsers.
We have released new book"Content Marketing in social networks: How to get into the head of subscribers and fall in love with your brand. "
JSON is a text-based data interchange format based on a multi-paradigm programming language. Its main purpose is to store and transmit a structured stream of information.
By using simple rules for constructing constructs from characters in JavaScript, a person can provide an easy and reliable way to store any kind of information, be it an ordinary number, whole strings, or a huge number of different objects expressed in plain text.
In addition, the JSON format is used to combine objects and data structures as a set of components, thereby forming program units that allow you to store and process complex records consisting of several variables of different types.
After the file is created, it is quite easy to redirect the lines contained in it to another location on the web through any data transmission path. This is because the string is plain text.
What does JSON mean
Although it can be used in almost all scripting languages, its name refers to JavaScript. The tool has the following advantages:
- It takes up a relatively small volume and is compact.
- Text content can be easily created and readable by computers and humans.
- Can be easily transformed into a structure for almost all kinds of formal languages used to create computer programs.
- Most programming languages, be they JavaScript, Ruby, Python, or PHP, have functions and special tools for reading and editing a file.
In the overwhelming majority of cases, the JSON format is used to work on transferring information from the server to the browser. This process, as a rule, occurs in the "background" mode of the browser exchange with the web server, and delivery is carried out using AJAX. This is because there is no need to reload the page during data delivery.
It works in the following scenario:
- For example, a user clicks on a product card in an online store.
- JavaScript built into the browser to make web pages more functional generates an AJAX request to a PHP script program file that runs on the server. Due to this, the ID of the selected product is transmitted.
- The PHP script program file accepts the product name, description, cost and other information that is contained in the database.
- After that, a string is formed and transmitted to the browser.
- JavaScript takes this string, restores the information it contains from its encoded representation, and then displays information about the selected product on the user's web page.
All this happens in a matter of milliseconds. However, if JavaScript is disabled on your computer for any reason, the web page will not load or display errors.
How the JSON format works
In JSON, data types fall into several categories: simple and complex. The first type includes, first of all, text strings and numbers, the second - objects. In total, there are six main types:
- Numeral. In this case, the numbers can be either unsigned integers or signed integers. In particular, it can contain the fractional part and the representation of real numbers in the form of the fractional part of the logarithm and order. The file equally allows the use of integers and floating point separation. This technique is used in JavaScript for all numeric values without exception, however, in other math libraries that use it, encoding can occur using completely different algorithms.
- An arbitrary sequence (string) of Latin alphabet characters, numbers and punctuation elements (from zero and unicode characters). Each subsequent line is separated from the previous line by means of a double punctuation mark - quotation marks ("text") or using a character, with the writing opposite to the usual character, a forward slash.
- Literals or constants included directly in the text. It can be any value between true and false, or their equivalents.
- Array. It is an ordered list of characters from zero onward. Each symbol can be presented in any form.
- An object. It is a randomly composed composition of key / value pairs. Given that the main function of objects is to represent an abstract data type, it is recommended (but optional) that keys be unique.
- An empty value indicated by the word "Null".
Character spacing is allowed if it will be used between syntactic units. Several symbols are used for this: the usual indent, horizontal text tabs, and the forward slash.
How to open JSON format
The textual data exchange format can be represented in popular coding standards, which make it possible to more compactly store and transfer Unicode characters. In particular, it defaults to UTF-8. UTF-16 and UTF-32 can also be used. Their use is due to the fact that all three standards support the entire character set.
But, if they are escaped (not quoting) to use them like regular expression, they can be written to represent characters in complementary planes using UTF-16.
The easiest way to open JSON format is to use Notepad on your PC. To do this, you need to create and open a new Text Document, select in the left upper corner File, then Open.
Having found the required document, you should click on the Explorer button "Open".
The document will open and will be available for viewing and editing.
In addition, there are third party programs to open JSON format. Among them are Altova XMLSpy, Notepad ++, Komodo Edit, Sublime Text, etc.
How to create a file
The JSON format is usually used to work (store and use) service information. Usually this staffing table, which neither the developer nor the audience of the web resource should see.
There are several ways to create a file with the appropriate extension. First of all, this can be done using a regular text editor, which is part of operating system Microsoft Windows... To do this, you need to open Notepad, insert the appropriate code and save the document in a regular and only available extension. After that, you need to change it to the desired option.
The second method involves the use of third-party services. The most popular is JSON Editor Online. It is much more convenient than the Notepad option. The service interface is presented in the form of two working areas.
In the first one, the work on the formation of data takes place directly, in the second zone the tools for this are placed. After the creation process is over, you need to click on the "Save" button and select the method of saving the result: to disk or online.
As noted, using an online service is much more convenient than Notepad. This is due to the fact that the service automatically detects syntax errors during operation and highlights them so that the user can notice omissions and correct them immediately.