How to set up smartphones and PCs. Informational portal
  • home
  • news
  • What is JSON? JSON format: example and description.

What is JSON? JSON format: example and description.

Consisting of attribute-value pairs. This is the most common data format used for asynchronous communication between the browser and the server, largely replacing XML (using AJAX).

JSON is a language independent data format that was derived from JavaScript. As of 2017, many programming languages ​​use code to generate and parse 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 the valid syntax, while the RFC covers some security and interoperability basics.

In addition, there is RFC 7493, which defines a restricted profile known as I-JSON (short for "Internet JSON"). It seeks to overcome some interoperability 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 plug-ins (such as Flash or Java applets).

Development and application

As already noted, Douglas Crockford, as the founder of StateSoftware, first identified and popularized the JSON format. Subsequently, the co-founders agreed to create a system using standard browser capabilities and provided an abstraction layer for developers to build applications with continuous duplex connectivity to the web server. At the same time, it became possible to keep two HTTP connections open and process them until the browser's standard working time if no data exchange was made. The co-founders held a roundtable discussion and voted to name the data format JSML or JSON, as well as determine the type of license under which the new development will be made 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 and commonly used in conjunction with a subset of the JavaScript scripting language (specifically, Standard ECMA-262 3rd Edition-December). However, this is a language-independent format. 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 originally advertised as being a strict subset of JavaScript and ECMAScript, it occasionally allows some characters that are not escaped in strings that are illegal in JavaScript and ECMAScript strings.

JSON itself became an ECMA international standard in 2013 as the ECMA-404 standard, which was used as a reference in RFC 7158 the same year. In 2014 RFC 7159 became the main reference for using 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 exponential E notation, but cannot include non-numbers (such as NaN). The format does not distinguish 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 larger Unicode characters. Strings are delimited by double quote characters and support the backslash syntax.
  • Literals: any of the 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 the names (also called keys) are strings. Since objects are intended to represent associative arrays, it is recommended (though not required) that each key be unique within it. Objects are separated by curly braces and use commas to separate each pair, while within each pair a colon character separates the key or name from its value.
  • Null: An empty value using the null word.

Delimited spaces are allowed and may be placed around or between syntax elements (meanings and punctuations, but not within a string value). For this purpose, only four special characters are considered spaces: space, horizontal tab, newline, and slash. In particular, the byte order mark need not be generated by the conforming implementation (although it may be accepted when parsing JSON). The JSON request does not provide syntax for comments.

Early 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 not currently used.

Data portability issues

Even though Douglas Crockford originally stated that JSON is a strict subset of JavaScript, its specification actually allows documents to be created that are unreadable in JavaScript. In particular, JSON allows the values ​​of the Unicode strings U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR to appear unescaped in quoted strings, while JavaScript does not. This is a consequence of the fact that JSON only disallows "control characters". For maximum compatibility, these characters must be escaped with a backslash. This subtlety is important when creating JSONP.

JSON format: how to open?

JSON documents can be encoded in UTF-8, UTF-16 or UTF-32, the default encoding is UTF-8. These standards support the full "Unicode" character set, including characters outside the Basic Multilingual Plane (U+10000 to U+10FFFF). However, if escaped, these characters must be written using UTF-16 surrogate pairs, a detail missed by some parsers of the JSON format. How to open and how such a file will be read?

Numbers in this format are agnostic about their representation in programming languages. There is no distinction 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 regarding issues such as overflow, underflow, loss of precision, or rounding. Also, the JSON format doesn't say anything about handling signed zeros, whether or not 0.0 is different from -0.0. Most implementations that use the IEEE 754 floating point standard, including JavaScript, preserve 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, the JavaScripteval function can be used to parse JSON data. Because of the problem with parsing Unicode string terminators discussed in the previous section, the eval function must replace them.

This is not safe if the string is not properly validated. Instead, you should use the JSON parser library or its JavaScript support to read and write JSON.

A properly implemented parser only accepts valid JSON format as defined by the system, preventing potentially malicious code from unintentionally executing.

Since 2010, web browsers such as Firefox and Internet Explorer have included support for parsing and uploading to JSON format.

Unsupported native data types

The 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 universally accepted. Other languages ​​may have a different set of native types, which must be carefully serialized to deal with this type of conversion.

JSON Schema

The schema is used to define the 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 in XSD, the same serialization/deserialization facilities are used for both schema and data.

Schema is an internet project 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 that .schema.json be approved.

MIME type

The official MIME type for JSON text is "application/json". Although most modern implementations have adopted an 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 remote procedure call (RPC) protocol built on JSON, 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 a 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, the JSON data format is the main one. AJAJ is a web development technology that enables a web page to request new data after being loaded into the browser. It usually renders them from the server in response to user actions on that page. For example, what the user enters into a search box, the client code then sends it to the server, which immediately responds with a drop-down list of matching database items.

Security issues

Text in JSON format is defined as a data serialization object. However, its design, as a loose subset of the JavaScript scripting language, introduces 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 working with data retrieved from the Internet.

This simple and popular, but risky, method uses compatibility with the JavaScripteval function.

Some developers mistakenly believe that JSON text is also syntactically similar to JavaScript code, although this is only partly 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 the JSON data, creating native JavaScript objects. However, this method is risky if there is a possibility that the JSON data may contain arbitrary "javascript" code, which will then be executed in the same way. If steps are not taken to validate the data first, the eval method is susceptible to security vulnerabilities where the data and the entire JavaScript environment are not under the control of a single trusted source.

For example, if data is not verified, it is attacked by malicious JavaScript code. Such breaches can also create the risk of data theft, authentication forgery, and other potential misuse of data and resources.

So the new JSON.parse function was designed as a safer alternative to eval. It is specifically designed to process JSON data, not JavaScript. It was originally planned to be included 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.

JSON (JavaScript Object Notation) is a format for exchanging textual data. Allowing you to transfer complex data structures in a serialized form. This data transfer format has become so popular that since version 5.2.0 of the PHP core, functions for processing data in this format have been added. And this means that there is no need to connect additional extensions. The JSON data format is well understood by a human. In addition, this type of data exchange is widely used between various API services. And with the correct development of algorithms for the exchange of information, you can get a very high speed increase than, for example, when working with data in XML format.

Sending data

There are two ways to send data in JSON format: form a GET or POST request with encoded data located in the GET or POST variable, or place the data in the body of the document. In practice, the second option is usually used.

To send data, the following functions are required:

  • string json_encode(mixed value [, int options = 0 ])

    The value parameter specifies the data to be encoded. Any type is supported except type resource. The options parameter contains a bitmask of the possible supplied values ​​(see table with JSON supplied constants).

  • resource stream_context_create (])

    This function is intended to create and return a thread context with the options specified in the options parameter. The optional options parameter must be an associative array type. Initially, it is empty. The second optional params parameter must also be an associative array in the format $data['name'] = value.

  • string file_get_contents(string filename [, bool use_include_path [, resource context [, int offset [, int maxlen ]]]])

    Using this function allows you to get the contents of a file as a string. The filename parameter is the name of the file being read. In the use_include_path parameter, starting from PHP 5, you can use the constant FILE_USE_INCLUDE_PATH to search for a file in the include path. The context parameter represents the context resource created with the stream_context_create() function. In case of an unsuccessful attempt to open the file, the value will be returned. false. The offset parameter contains the offset from which to start reading the data. The maxlen parameter specifies the size of the received data.

    Note: offset is not specified when working with remote threads.

The following is an example of sending data in JSON format:

// Data to send $request = array("StartDate" => "2013-10-10", "EndDate" => "2013-10-10", "IDS" => array(1,2,3,4 ,5,6,7)); // Specifying options for the stream context $options = array ("http" => array ("method" => "POST", "header" => "Content-Type: application/json; charset=utf-8\r\ n", "content" => json_encode($request))); // Create a stream context $context = stream_context_create($options); // Sending data and getting the result echo file_get_contents("http://test.ru/json.php", 0, $context);

It uses an improvised data structure consisting of a start and end date, as well as an array of numbers of some conditional records. Notice that in the request header content-type the type "application/json" is specified.

Getting data

In order to receive the transferred data in the manner described above, it is required to read the data from the input stream “ php://input”.

Functions used to accept data:

  • mixed json_decode(string json [, bool assoc = false [, int depth = 512 [, int options = 0 ]]])

    This function decodes a JSON string. The json parameter specifies the string to be decoded. The assoc parameter controls whether the returned data will be converted to an associative array. If there is such a need, then you must specify as the value of this parameter true. The depth parameter indicates the depth of the recursion. And the last fourth parameter options contains the bitmask of the options to decode. Currently only supported JSON_BIGINT_AS_STRING(by default, large integers are converted to floating point numbers (float))

  • resource fopen(string filename , string mode [, bool use_include_path [, resource context ]])

    Opens a file and returns its handle. The filename parameter is a named resource pointing to a file. The mode parameter specifies the type of access to the file (see the table for a list of possible modes for fopen()). Next are two optional parameters: use_include_path and context . When setting the use_include_path parameter to true or 1 and provided that a relative path is specified as a named resource, the file to be opened will be searched in the list of directories used by the functions include and require. In practice, this parameter is practically not used. The context parameter is used to specify the context of the resource.

  • string stream_get_contents(resource handle [, int maxlen = -1 [, int offset = -1 ]])

    This function allows you to get the contents of the stream as a string. The handle parameter is a stream resource. The maxlen parameter contains the maximum number of bytes to read. By default, it is set to -1, which indicates that all data is received. The offset parameter contains the offset from which to start reading the data. It is also set to -1 by default, which means it will read from the starting position.

The following is an example of getting data in JSON format on the server side:

// Open the input stream for reading $f = fopen("php://input", "r"); // Get the content of the stream $data = stream_get_contents($f); if ($data) ( // Processing code print_r(json_decode($data)); )

The resulting data structure:

StdClass Object ( => 2013-10-10 => 2013-10-10 => Array ( => 1 => 2 => 3 => 4 => 5 => 6 => 7))

Note: it is necessary to take into account the fact that in order to work with the JSON format, the data must be encoded in utf-8.

JSON-provided constants for the json_encode() function

JSON_HEX_TAG (integer) All are encoded in \u003C and \u003E. Available since PHP 5.3.0.
JSON_HEX_AMP (integer) All &s are encoded in &. Available since PHP 5.3.0.
JSON_HEX_APOS (integer) All characters ‘ are encoded in \u0027. Available since PHP 5.3.0.
JSON_HEX_QUOT(integer) All characters " are encoded in \u0022. Available since PHP 5.3.0.
JSON_FORCE_OBJECT(integer) Return an object instead of an array when using a non-associative array. This is useful when the receiving program or code is expecting an object or the array is empty. Available since PHP 5.3.0.
JSON_NUMERIC_CHECK(integer) Encoding strings containing numbers as numbers. Available since PHP 5.3.3.
JSON_BIGINT_AS_STRING(integer) Encodes large integers as their string equivalents. Available since PHP 5.4.0.
JSON_PRETTY_PRINT(integer) Use whitespace characters in the returned data to format it. Available since PHP 5.4.0.
JSON_UNESCAPED_SLASHES (integer) Do not escape /. Available since PHP 5.4.0.
JSON_UNESCAPED_UNICODE(integer) Do not encode multibyte Unicode characters (by default they are encoded as \uXXXX). Available since PHP 5.4.0.

List of possible modes for fopen() using mode

‘r’ Opens a read-only file; places the pointer at the beginning of the file.
‘r+’ Opens a file for reading and writing; places the pointer at the beginning of the file.
'w' Opens a file for writing only; places the pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, it tries to create it.
'w+' Opens a file for reading and writing; places the pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, it tries to create it.
‘a’ Opens a file for writing only; places a pointer at the end of the file. If the file does not exist, it tries to create it.
‘a+’ Opens a file for reading and writing; places a pointer at the end of the file. If the file does not exist, it tries to create it.
'x' Creates and opens for writing only; places the pointer at the beginning of the file. If the file already exists, the fopen() call will fail, return FALSE, and throw an E_WARNING level error. If the file does not exist, it will try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flags for the internal open(2) system call.
'x+' Creates and opens for reading and writing; otherwise has the same behavior as 'x'.
'c' Opens a file for writing only. If the file does not exist, then it is created. If the file exists, then it is not truncated (unlike 'w'), and a call to this function does not raise an error (same as in the case of 'x'). The file pointer will be set to the beginning of the file. This can be useful if you want to lock the file (see flock()) before changing it, since using 'w' can truncate the file before the lock has been acquired (if you want to truncate the file, you can use the ftruncate() function after the lock request ).
'c+' Opens a file for reading and writing; otherwise has the same behavior as 'c'.

JavaScript allows us not only to add interactivity to web pages, but makes it possible to perform tasks that once belonged to servers. JSON provides an easy way to create and store structured data in JavaScript. JSON is very popular and is a great alternative to XML. JSON (JavaScript Object Notation), as the name suggests, is based on creating javascript objects. JavaScript objects can be easily manipulated, parsed using the same JavaScript.

Unlike XML, JSON sentences are easily composed by both humans and computers. Data in JSON format can, for example, be assigned to a variable (this is how we create an object); this data can then be read through the newly created object.

First, we create a variable to hold our data, and then we define an object using JSON. Our object is pretty simple: a firstName field and a Ray value. Strings in JSON must be enclosed in quotation marks. If you are using numbers, the quotes are optional.

This example will display the value of the firstName property in the browser.

Creating a placeholder object

Let's create a more realistic example: insert our JSON data into a DOM object.

var data=("firstName":"Ray"); document.getElementById("placeholder").innerHTML=data.firstName;

Now, instead of displaying a warning, we put the data inside the HTML element. JSON data can of course be much more complex. Let's try to add some more fields.

data=( "firstName":"Ray", "lastName":"Villalobos", "joined":2012 ); document.getElementById("placeholder").innerHTML=data.firstName+" "+data.lastName+" "+data.joined;

Note that the JSON data is formatted in a certain way for better understanding. The "joined" field is 2012, which doesn't need quotes because it's a number. Let's look at something more complex.

Adding Arrays

What if we want to enter a group of people...then we need to use arrays. An array in JSON can be created using square brackets. Let's see how our data will look for several users.

Var data=("users":[ ( "firstName":"Ray", "lastName":"Villalobos", "joined":2012 ), ( "firstName":"John", "lastName":"Jones", "joined":2010 ) ]) document.getElementById("placeholder").innerHTML=data.users.firstName + " " + data.users.lastName+" "+ data.users.joined;

It looks a little more complicated, but it's actually not hard to understand. The JSON object is created using curly braces; an array is created using square brackets. So, in order to organize our data, we created a users object and put an array in it. The array contains other objects. Each (name/value) pair is separated by a comma.

Notice how the name insertion code has changed. We've included a new users object and then used square brackets to point to the first element in the array. Let's add one more layer to our data structure.

Var data=("users":[ ( "firstName":"Ray", "lastName":"Villalobos", "joined": ( "month":"January", "day":12, "year":2012 ) ), ( "firstName":"John", "lastName":"Jones", "joined": ( "month":"April", "day":28, "year":2010 ) ) ]) document. getElementById("placeholder").innerHTML=data.users.firstName + " " + data.users.lastName+"--"+ data.users.joined.month;

The joined property now contains an object with multiple fields; there is no need to use an array, so we use object notation. Now we have data for several users, it's time to go through each user and display them in the list.

Implementing a list of users (traversing the JSON object)

So let's use javascript and create a list of users.

Var data = ( "users":[ ( "firstName":"Ray", "lastName":"Villalobos", "joined": ( "month":"January", "day":12, "year":2012 ) ), ( "firstName":"John", "lastName":"Jones", "joined": ( "month":"April", "day":28, "year":2010 ) ) ]) var output ="

    "; ) output+="
"; document.getElementById("placeholder").innerHTML=output;

To enumerate all the properties of an object, there is a construction for..in:

For(var key in object) ( // key - property name // object - property value... )

Here we are iterating over all the elements of the array; we store the data in the output variable and put the data in the element with id equal to placeholder . you can tell that our data is building a bit slowly.

Read JSON from external file

It would be nice to save the data to an external file and read it as needed. I'm going to be using the jQuery library, so first we need to include the jQuery library; then call the getJSON function. Here's what our code looks like:

JSON sample

Pretty much the same code, but the data is pushed out. We just wrapped everything in a getJSON function that does all the hard work of reading the file. The data file data.json is supposed to be in the same directory and looks like this:

("users":[ ( "firstName":"Ray", "lastName":"Villalobos", "joined": ( "month":"January", "day":12, "year":2012) ), ( "firstName":"John", "lastName":"Jones", "joined": ( "month":"April", "day":28, "year":2010 ) ) ])

As you can see, JSON is really easy to read, and once you get used to the parentheses, it becomes easy to code.

JSON has been part of the ECMAScript standard since 1999, when ECMA defined the eval() function to accept the format. It began to gain popularity along with the growing success of Ajax. The word JSON often comes up when someone talks about Ajax. It is known that JSON is a different data format, that it is replacing XML, and that many programmers actively support it. But what exactly is JSON and what are its benefits?

Why JSON?

The advantage of JSON is that it is recognized by JavaScript. There is no need to parse the document, as is the case with XML, to transfer data over the Internet.

JSON and XML

Benefits of JSON:

  • Easy to read and understand.
  • Easy to use.

Advantages of XML:

  • Has expandability

Both XML and JSON have the ability to integrate a large amount of data in binary form.

JSON Syntax

JSON Components:

  • Objects: contain objects or attributes.
  • Scalar variables: number, string, boolean.
  • Array.
  • Literal values: null, true, false, "character string", and numeric values.

An object

Contains an element or a list of elements, where each element is described as follows:

"name" : "value"

Object syntax:

( element, element, .... )

array

A set of values ​​separated by a comma.

[value, value, ....]

Meaning

The value can be: an object, an array, a literal value (string, number, true, false, null).

Nothing else is needed to create a JSON file!

JSON file example

A simple menu structure example. This object contains attributes and an array that includes other menu bar objects.

( "menu": "File", "commands": [ ( "title": "New", "action":"CreateDoc" ), ( "title": "Open", "action": "OpenDoc" ), ( "title": "Close", "action": "CloseDoc" ) ] ) XML equivalent:

File New</value> <action>CreateDoc</action> </item> <item> <title>Open</value> <action>opendoc</action> </item> <item> <title>close</value> <action>CloseDoc</action> </item> </commands> </root> </p><h3><span>How to use the format</span></h3> <p>The JSON file allows you to upload data from or to a server. For example, saving the contents of a form that has just been filled in by the user. The process includes three phases: processing by the browser, processing by the server, and data exchange between them.</p> <h4><span>Client side (browser)</span></h4> <p>This part is quite simple, since JSON is part of the JavaScript definition. The contents of a file or defining data are assigned to variables and they become program objects.</p> <h4>Server part</h4> <p>The JSON file is used by various programming languages, including PHP and Java, due to the presence of parsers that allow you to get the content and even convert it into language classes and attributes. On the JSON site, you can find parsers for many programming languages.</p> <h4>Data exchange</h4> <ul><li><span>using XMLHttpRequest.</span></li> </ul><p>JSON file is parsed by JavaScript function <i>eval()</i>. Sending a file to the server can be done using XMLHttpRequest . The file is sent as a text file and is processed by the programming language parser used on the server.</p> <h3>Example</h3> <p>XMLHttpRequest code:</p><p>varreq = new XMLHttpRequest(); req.open("GET", "file.json", true); req.onreadystatechange = myCode; // handler req.send(null);</p><p>JavaScript handler:</p><p>Function myCode() ( if (req.readyState == 4) ( var doc = eval("(" + req.responseText + ")"); ) ) Using data: var menuName = document.getElementById("jsmenu"); // look for the field menuName.value = doc.menu.value; // assign a value to the field How to get data: doc.commands.title // read the value of the "title" field in the array doc.commands.action // read the value of the "action" field in the array</p> <p><i>A lesson that looks at what JSON is and what advantages it has over other data formats.</i></p> <h2>Understanding JSON</h2> <p>JSON (JavaScript Object Notation) is a text format for representing data in JavaScript object notation.</p> <p>This means that the data in JSON is organized in the same way as in a JavaScript object. But unlike the latter, the JSON recording format has some features that will be discussed a little later.</p> <p>JSON is usually used in conjunction with AJAX so that the server can pass data in a convenient form to a JavaScript script, which will then display it on the page.</p> <h2>JSON Format Structure</h2> <p>Those who are 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.</p> <p>It's easier to think of JSON as a container of elements. Each element in such a container is some structural unit consisting of a key and a value.</p> <p><img src='https://i2.wp.com/itchief.ru/assets/images/tickets/2015.12/javascript-structure-json.png' align="center" width="100%" loading=lazy loading=lazy></p> <p>In this case, the value is directly related to the key and form the so-called key-value pair. In order to get a value in such an object, you need to know its key. Syntactically, such data in JSON is written as follows:</p> <p><img src='https://i2.wp.com/itchief.ru/assets/images/tickets/2015.12/javascript-json-syntax-data.png' align="center" width="100%" loading=lazy loading=lazy></p> <p>In the above entry, you can see that the key is separated from the value with 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 distinguishes it from a JavaScript object. Because in a JavaScript object, the key (object property) does not need to be enclosed in double quotes.</p> <p><i> </i> For example, an object structure that is valid from a JavaScript perspective but not valid from a JSON perspective:</p><p>Var person = ( name: "John"; ) // JavaScript object</p><p>Warning: try to set the key name in such a way as not to complicate data access, i.e. when composing a name, it is preferable to use camel case notation or use an underscore ("_") to connect words.</p> <p>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 (JavaScript special value).</p> <p>This <b>second limitation in JSON, because a JavaScript object can contain any type of data, including a function</b>.</p><p>Var person = ( "name" : "John"; "setName": function() ( console.log(this.name); ) ) // JavaScript object</p><p>A comma (,) is used to separate one element (key-value pair) from another.</p> <p>For example, consider a JSON consisting of various data types.</p> <p><img src='https://i0.wp.com/itchief.ru/assets/images/tickets/2015.12/javascript-json-types-data.png' align="center" height="682" width="543" loading=lazy loading=lazy></p> <p> <i> </i> Attention: the JSON data representation format does not allow the use of comments within its structure.</p> <h2>Working with JSON in JavaScript</h2> <p>Unlike a JavaScript object, JSON is a string.</p> <p>For instance:</p><p>// for example, the personData variable 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)";</p><p>Working with JSON is usually carried out in two directions:</p> <ol><li>Parsing is the translation of a string containing JSON into a JavaScript object.</li> <li>Converting a JavaScript object to a JSON string. In other words, this action does the reverse of parsing.</li> </ol><h3>Parsing JSON</h3> <p>JSON parsing, i.e. translating a JSON string into a JavaScript object is done using the eval() or parse() method.</p> <p>Using the eval() method:</p><p>// the person variable is a JavaScript object that is obtained by executing the JSON code (string) var person= eval("("+personData+")");</p> <p>Using the JSON.parse() method:</p><p>// the person variable is a JavaScript object that is obtained by parsing a JSON string var person = JSON.parse(personData);</p><h3>Converting a JavaScript Object to a JSON String</h3> <p>Translating a JavaScript object into a JSON string is done using the JSON.stringify() method. This method does the opposite of the JSON.parse() method.</p><p>Var personString = JSON.strigify(person);</p><h2>Benefits of the JSON format</h2> <p>The JSON data representation format has the following advantages:</p> <ul><li>convenient and fast methods for converting (parsing) a JSON string into a JavaScript object and vice versa;</li> <li>clear and simple data structure;</li> <li>very small size compared to other data formats (eg XML). This is because the JSON format contains the minimum possible formatting, i.e. when writing it, only a few special characters are used. This is a very important advantage, because data presented in JSON format will load faster than if it were presented in other formats.</li> </ul><p>Due to the fact that this format has a lot of advantages, it has become used not only in JavaScript, but also in many other languages, such as C, Ruby, Perl, Python, PHP, etc.</p> <h3>Comparison of JSON and XML formats</h3><p>The JSON format has the following advantages over the XML format:</p> <ol><li>When passing some data, the JSON size will be significantly smaller than the XML size.</li> <li>JSON has more convenient methods for converting to JavaScript data structures than XML.</li> <li>JSON is easier to create than XML.</li> </ol><p><img src='https://i1.wp.com/itchief.ru/assets/images/tickets/2015.12/json-vs-xml.png' align="center" width="100%" loading=lazy loading=lazy></p> <p>Working with JSON data after parsing is done as with a JavaScript object.</p><p>//JSON var personData = "("name":"Ivan","age":37,"mother":("name":"Olga","age":58),"children":["Masha" ,"Igor","Tanya"],"married": true,"dog": null)"; //JavaScript person object var person = JSON.parse(personData);</p><p>Consider the main points:</p><p>//get the values ​​of the key (property) name person.name; person["name"]; //get the values ​​of the key (property) name, located in the object mother person.mother.name; //delete age element delete(person.age) //add (or update) 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("Kate");</p><p><img src='https://i0.wp.com/itchief.ru/assets/images/tickets/2015.12/javascript-woks-with-json-after-parsing.png' align="center" width="100%" loading=lazy loading=lazy></p> <p>To iterate over the elements in an object, you can use a for..in loop:</p><p>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 keys (properties) in the object</p><p><img src='https://i0.wp.com/itchief.ru/assets/images/tickets/2015.12/javascript-for-in-object.png' align="center" height="173" width="371" loading=lazy loading=lazy></p> <p>You can use the following loop to iterate over the elements of an array:</p><p>For (var i=0; i</p><p><img src='https://i0.wp.com/itchief.ru/assets/images/tickets/2015.12/javascript-for-in-array.png' align="center" height="115" width="253" loading=lazy loading=lazy></p> <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast_after?t44.1;r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";h"+escape(document.title.substring(0,150))+ ";"+Math.random()+ "border='0' width='1' height='1' loading=lazy loading=lazy>");</script> </div> <div class="post-social-counters-block"> <div style="margin-top: 12px"> <noindex></noindex> </div> </div> </div> </div> <a name="comments"></a> <h3 class="best-theme-posts-title">Top Related Articles</h3> <div class="container-fluid"> <div class="best-theme-posts row"> <div class="theme-post col-sm-4"> <a href="https://bumotors.ru/en/chto-delat-esli-iphone-vklyuchaetsya-i-srazu-vyklyuchaetsya-pochemu-ne.html"> <div class="img_container"><img src="/uploads/c0136026eec9c910153ee568b0006602.jpg" border="0" alt="Why the iPhone does not turn on: what to do when the apple is on and the iPhone 4 turns off and turns on and off what to do" width="320" height="180" / loading=lazy loading=lazy></div> <span class="theme-post-link">Why the iPhone does not turn on: what to do when the apple is on and the iPhone 4 turns off and turns on and off what to do</span> </a> </div> <div class="theme-post col-sm-4"> <a href="https://bumotors.ru/en/pochemu-vy-dolzhny-nakleit-zashchitnoe-steklo-na-iphone-x-pryamo-seichas-kak.html"> <div class="img_container"><img src="/uploads/c5792415809908dad1d0a752c3cdd71f.jpg" border="0" alt="How to stick a protective glass on a smartphone How to stick a protective glass on an iPhone 5" width="320" height="180" / loading=lazy loading=lazy></div> <span class="theme-post-link">How to stick a protective glass on a smartphone How to stick a protective glass on an iPhone 5</span> </a> </div> <div class="theme-post col-sm-4"> <a href="https://bumotors.ru/en/mozhet-li-nub-nakleit-zashchitnoe-steklo-na-iphone-nuzhno-li-kleit.html"> <div class="img_container"><img src="/uploads/384223378031904b4e949fcb58327f41.jpg" border="0" alt="Do I need to glue the protective glass on the iPhone?" width="320" height="180" / loading=lazy loading=lazy></div> <span class="theme-post-link">Do I need to glue the protective glass on the iPhone?</span> </a> </div> </div> </div> </div> <a name="comments"></a> </div> <div class="right-column col-sm-4 col-md-4"> <div class="write"> <span class="tags-title">Categories:</span> <ul style="height: 286px;" id="right-tags" data-tagscount="18" data-currentmaxtag="10" class="tags"> <li class=""><a href="https://bumotors.ru/en/category/programs/">Programs</a></li> <li class=""><a href="https://bumotors.ru/en/category/safety/">Safety</a></li> <li class=""><a href="https://bumotors.ru/en/category/windows-10/">Windows 10</a></li> <li class=""><a href="https://bumotors.ru/en/category/iron/">Iron</a></li> <li class=""><a href="https://bumotors.ru/en/category/windows-8/">Windows 8</a></li> <li class=""><a href="https://bumotors.ru/en/category/vkontakte/">In contact with</a></li> <li class=""><a href="https://bumotors.ru/en/category/errors/">Mistakes</a></li> </ul> </div> <div class="banner"> </div> </div> </div> </div> <div style="clear:both"></div> </div> <div class="footer"> <div class="subscribe"> <div class="main-wrapper container"> <div class="row"> <div class="col-sm-8"> </div> <div class="col-sm-4"> <div class="social"> <a href="" class="vk social-ico"></a> <a href="https://facebook.com/" class="fb social-ico"></a> <a href="https://twitter.com/" class="tw social-ico"></a> </div> </div> </div> </div> </div> <div class="info"> <div class="main-wrapper container"> <div class="row"> <span class="footer-info col-xs-12">© 2022 bumotors.ru. How to set up smartphones and PCs. Informational portal.</span> </div> </div> </div> </div> </body> </html>