Basics of working with JSON. JavaScript - JSON and methods of working with it In the json format, the array is one-dimensional

JSON(JavaScript Object Notation) - simple format data exchange, easy to read and write by both humans and computers. It is based on a subset of the JavaScript programming language, defined in the ECMA-262 3rd Edition - December 1999 standard. JSON is a text format that is completely independent of the implementation language, but it uses conventions familiar to programmers of C-like languages ​​such as C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data interchange language.

JSON is based on two data structures:

  • A collection of key/value pairs. In different languages, this concept is implemented as an object, record, structure, dictionary, hash, named list, or associative array.
  • An ordered list of values. In most languages ​​this is implemented as array, vector, list or sequence.

These are universal data structures. Almost all modern programming languages ​​support them in some form. It is logical to assume that a data format, independent of the programming language, should be based on these structures.

In JSON notation it looks like this:

An object- an unordered set of key/value pairs. An object begins with ( an opening curly brace and ends with a ) closing curly brace. Each name is followed by: a colon, key/value pairs separated by a comma.

Array- an ordered collection of values. The array begins with a [ open square bracket and ends with ] a closing square bracket. Values ​​are separated by comma.


Meaning May be line in double quotes, number, true , false , null , object or array. These structures can be nested.


Line- a collection of zero or more Unicode characters enclosed in double quotes, using \ backslash as the escape character. The character is represented as a one-character string. Similar syntax is used in C and Java.


Number It is represented in the same way as in C or Java, except that only the decimal number system is used.


Spaces can be used between any tokens.

Excluding some coding details, the above completely describes the language.


JSON(JavaScript Object Notation, JavaScript object notation) is a structured data representation format used for transmitting data over the Internet.

Essentially, the JSON format is a regular string.

JSON syntax

JSON syntax is quite small, it only includes a description of what the data being transferred looks like.

JSON data types

In JSON, data types can be divided into two categories: simple and complex.

  • string– text strings (usually they are simply called strings)
  • number– numbers
  • boolean– logical (Boolean) values
  • null

Complex types include:

  • object– objects
  • array– arrays

JSON syntax is borrowed from JavaScript, so it uses the same syntax as JavaScript to represent values ​​of simple and complex types.

Simple values

The simplest example JSON code – any value of a simple type:

5 2.3 "Hello!" true null

In JSON, strings must only be enclosed in double quotes. Using single quotes results in a syntax error.

Objects

A JSON object is a comma-separated list of zero or more properties (name: value pairs) enclosed in curly braces. Object property names must be enclosed in double quotes. Missing double quotes or using single quotes in a property name is an error. Properties can contain values ​​of any type (simple or complex):

("name": "Homer", "age": 40, "work": ("place": "Nuclear Plant", "location": "Springfield"))

Arrays

A JSON array is a comma-separated list of zero or more values, enclosed in square brackets. The array can contain values ​​of any type (simple or complex):

[ ( "name": "Homer", "age": 40, "work": ( "place": "Nuclear Plant", "location": "Springfield"), "children": [ "Bart", "Lisa" ", "Maggie" ]), ( "name": "Marge", "age": 37, "work": ( "place": "Home", "location": "Springfield"), "children": [ "Bart", "Lisa", "Maggie" ] ) ]

Consisting of attribute-value pairs. It 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. 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 was subsequently defined by two competing standards (RFC 7159 and ECMA-404) in 2013. The ECMA standard describes only valid syntax, while the RFC covers some basic security and interoperability.

Additionally, there is a standard called RFC 7493 that 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 plugins (such as Flash or Java applets).

Development and Application

As already noted, Douglas Crockford, being the creator of the StateSoftware company, first identified and popularized the JSON format. The co-founders subsequently agreed to create a system that used standard browser capabilities and provided an abstraction layer for developers to create applications with a continuous full-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 browser operating time if no data was exchanged. The co-founders held a round table discussion and voted to name the data format JSML or JSON, as well as determine the type of license under which the new development would be made available. The format is currently open source.

Practical use

The JSON.org website was launched in 2002. In December 2005, Yahoo! began 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 was commonly used in conjunction with a subset of the JavaScript scripting language (specifically Standard ECMA-262 3rd Edition-December). However, this is a data 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 promoted and considered a strict subset of JavaScript and ECMAScript, it periodically allows some characters not escaped in strings that are not valid in JavaScript lines and ECMAScript.

JSON itself has become international standard ECMA in 2013 as the ECMA-404 standard, which was used as a reference in RFC 7158 that same year. In 2014, RFC 7159 became the primary reference for the use of JSON on the Internet (eg 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 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 quotes and support backslash syntax.
  • Literals: any of 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. Because objects are meant to be represented 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, a colon character separates the key or name from its value.
  • Null: An empty value using the word null.

Limited white space is allowed and can be placed around or between syntactic elements (values ​​and punctuation, but not within a string value). For this purpose only four special characters The following are considered spaces: space, horizontal tab, newline, and forward slash. In particular, the byte order mark does not need to be generated by the corresponding implementation (although it may be accepted when parsing JSON). A JSON request does not provide syntax for comments.

Early versions (such as those specified in RFC 4627) required that a valid document consist only 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 argued that JSON is a strict subset of JavaScript, its specification actually allows documents to be created that are unreadable by JavaScript. In particular, JSON allows the Unicode string values ​​U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR to appear unescaped in quoted lines, but JavaScript does not. This is a consequence of JSON only disallowing "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 core 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 JSON format parsers. How to open and how will such a file be read?

Numbers in this format are agnostic regarding 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. Additionally, there are no requirements regarding issues such as overflow, underflow, loss of precision, or rounding. Additionally, the JSON format says nothing about handling signed nulls, regardless of whether 0.0 is other than -0.0. Most implementations using the IEEE 754 floating point standard, including JavaScript, preserve signed zeros, but not all JSON implementations can do so.

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 JSON data. Because of the problem with parsing Unicode string terminators discussed in the previous section, the eval function must perform their replacement.

This is unsafe unless the string is properly validated. Instead, you should use a JSON parser library or JavaScript support to read and write JSON.

A properly implemented parser will only accept valid JSON format, the description of which is present on the system, preventing unintentional execution of potentially malicious code.

Since 2010, in web browsers such as Firefox and Internet Explorer support for analysis and export 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 some others. These types JavaScript data 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

The schema serves 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 change it.

Schema is based on concepts from XML Schema (XSD), but is proprietary. Like 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 assert.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 appears as "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, designed as a replacement for XML-RPC or SOAP. It is a simple protocol that defines only a few data types 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.

A.J.A.J.

Asynchronous JavaScript and JSON (or AJAJ) refer to the same dynamic web page methodology as Ajax, but instead of XML, JSON is the primary data format. AJAJ is a web development technology that enables a web page to request new data after loading into the browser. It usually displays them from the server in response to user actions on that page. For example, what the user types into a search field is then sent by the client code 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, creates several security issues. 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 JavaScript code, although this is only partly true. Therefore, it is believed that a simple 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 parser itself is thus used to execute the JSON data, creating natural JavaScript objects. However, this method is risky if there is a possibility that JSON data may contain arbitrary Javascript code, which will then be executed in the same way. Unless steps are taken to validate the data first, the eval method is susceptible to security vulnerabilities when the data and the entire JavaScript environment are not under the control of a single trusted source.

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

Thus, new feature JSON.parse was designed as a more secure alternative to eval. It is specifically designed to process 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.

JSON syntax is a subset of JavaScript syntax.

JSON syntax rules

The JSON syntax is derived from the JavaScript notation object syntax:

  • Data in name/value pairs
  • Data separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON data - name and value

JSON data is written as name/value pairs.

A name/value pair consists of the field name (in double quotes) followed by a colon, followed by the value:

example

"firstName":"John"

JSON names require double quotes. There are no JavaScript names.

JSON values

JSON values ​​can be:

  • Row (integer or floating point)
  • String (in double quotes)
  • Boolean (true or false)
  • Array (in square brackets)
  • Object (in curly braces)

JSON objects

JSON objects are written in curly braces.

Just like JavaScript, JSON objects can contain multiple name/value pairs:

example

("firstName":"John", "lastName":"Doe")

JSON Arrays

JSON arrays are written in square brackets.

Just like JavaScript, a JSON array can contain multiple objects:

example

"employees":[

("firstName":"Peter","lastName":"Jones")
]

In the example above, the "employees" object is an array containing three objects. Each object represents a person's record (with first and last name).

JSON uses JavaScript Syntax

Since JSON syntax is derived from JavaScript object notation, there is very little additional software necessary for working with JSON in JavaScript.

With JavaScript you can create an array of objects and assign data to it like this:

example

var employees = [
("firstName":"John", "lastName":"Doe"),
("firstName":"Anna", "lastName":"Smith"),
("firstName":"Peter","lastName": "Jones")
];

The first entry into an array of JavaScript objects can be obtained as follows:

You can also get it like this:

The data can be changed as follows:

It can also be changed as follows:

In the next chapter, you will learn how to convert JSON text to JavaScript object.

files in JSON format

  • The file type for JSON files is ".json"
  • MIME type for JSON text "application/json"

JSON is a text format for recording data. It allows you to represent in text form both a single number or string, and complex structures, for example, arrays with data. Using this recording format is convenient because it is readable and intuitive, while at the same time allowing you to store very complex data structures. In addition, it is more compact than xml, so in my opinion it is more preferable for exchanging data between a web browser and a server.

JSON syntax with examples

The json format is usually written in 2 variants:

1. Sequence of values. For example, the sequence 10, 15 and "test" in JSON format would look like this:

2. Recording in pairs key: value . For example:

(“Full name”: “Ivanov Sergey”, “Date of birth”: “03/09/1975”)

A slightly more complex example:

("Full Name": "Ivanov Sergey", "Address": ("City": "Moscow", "Street": "Pyatnitskaya", "House": "35") )

PHP functions for working with JSON format

IN php language starting from version 5.2. there are only 4 functions:

  • json_decode- Decodes a JSON string (gets data from a json format string)
  • json_encode- Returns a JSON representation of the data (converts the data to a JSON string)
  • json_last_error_msg- Returns a string indicating the error message of the last call to json_encode() or json_decode()
  • json_last_error- Returns the last error

Basically, for the most part, only two functions are used: json_encode And json_decode. I won’t go into details of their syntax, you can look at php.net for more details. Usage example:

$arr1 = array(0,1,2); $json_str = json_encode($arr1); echo $json_str; // will output a json string: $arr2 = json_decode($json_str); echo $arr2; // will output: 1

note : at encoding into JSON data format in Russian, the json_encode function converts Russian characters to unicode, i.e. replaces them with \uXXXX and thus the json string becomes unreadable for humans (but understandable for the browser). If you want to avoid conversion to Unicode (for example, when debugging code), you can simply use the JSON_UNESCAPED_UNICODE option.

Also, so that escaping slashes are not added during encoding and so that strings with numbers are encoded as numbers, you can use JSON_UNESCAPED_SLASHES and JSON_NUMERIC_CHECK. As a result, to make the json string human readable, we will do, for example, this:

$arr = array("fio" => "Ivanov Sergey", "age" => "32", "vk_url" => "https://vk.com/id11111"); echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

Without using these options the line would be like this:

( "fio" : "\u0418\u0432\u0430\u043d\u043e\u0432 \u0421\u0435\u0440\u0433\u0435\u0439", "age" : "32", "vk_url": "https:\/\ /vk.com\/id11111" )

and using the options, we get a readable line:

( "fio" : "Ivanov Sergey", "age" : 32, "vk_url" : "https://vk.com/id11111" )

One more point: if you need the function to decode a json string json_decode returned exactly the array, just add a second parameter to the function equal to true.

$json_str = "( "a":1, "b":2, "c":3 )"; $obj = json_decode($json_str); // get the object echo $obj->a; // will output 1 $arr = json_decode($json_str, true); // get an associative array echo $arr["a"]; // will print 1

This concludes my review of PHP functions.

JavaScript functions for working with JSON format

Let's start with the fact that the JSON format was originally invented for the JavaScript language and then became simply a separate text format, used in different languages. Apparently, this is why the JSON syntax is very similar to the syntax for writing ordinary objects and arrays.

// Example of an array in JavaScript arr = ; alert(arr); // will display 1 // Example of an object in JavaScript obj = ( "name": "Vasya", "age": 35, "isAdmin": false ) alert(obj.name); // will print "Vasya"

JavaScript functions used to convert to and from JSON format:

  • JSON.parse- decoding JSON string (converting string to objects and/or arrays)
  • JSON.stringify- returns a JSON representation of data (converting objects and/or arrays to a json string)

A simple example of decoding a json string into an array with numbers:

Str = ""; arr = JSON.parse(str); alert(arr); // will print 1

An example of converting (serializing) an object to a JSON string:

Obj = ( "name": "Vasya", "age": 35, "isAdmin": false ) alert(JSON.stringify(obj)); // will display ("name":"Vasya","age":35,"isAdmin":false)

When serializing (converting) an object into a JSON string, the method is called toJSON this object, if it exists. If there is no method, then all properties of the object are listed. An example of converting an object with the toJSON method:

Obj = ( "name": "Vasya", "age": 35, "isAdmin": false, toJSON: function() ( return this.age; ) ) alert(JSON.stringify(obj)); // will print 35

Examples of practical application of the JSON format

Actually, I personally use the JSON format in 2 main situations:

1. Transferring data between the browser and the server using Ajax requests.

For example, we have some page on which we need to update data without reloading the page. Let’s say you need information with a list of employees and their data to be “downloaded” from the server.

In JavaScript with using jQuery make it simple and display the data in the form of a table in the browser:

$.getJSON("get-info.php").success(function(data) ( // ajax request, data from the server will be written to the data variable htmlstr = "

"; for (var i=0; i "; // first column - full name htmlstr += " "; // second column - Date of birth htmlstr += ""; ) htmlstr = "
" + data[i].birthday + "
"; $("div.info").html(htmlstr); // in a div with the info class we display the resulting table with data ));

On the server, the get-info.php script to which an ajax request is made could, for example, be like this:

$user_info = array(); // create an array with data $user_info = array ("fio" => "Ivanov Sergey", "birthday" => "03/09/1975"); $user_info = array ("fio" => "Alexey Petrov", "birthday" => "09/18/1983"); echo json_encode($user_info); exit;

In this example, the JSON string that was passed from the server to the browser was like this:

[("fio":"Sergey Ivanov","birthday":"03/09/1975"),("fio":"Alexey Petrov","birthday":"09/18/1983")]

I deliberately did not show the line in the form of a “tree”, because it is transmitted exactly in this form. And how can you evaluate, recording data in JSON format turned out to be very compact, which means that the transfer of this data from the server to the browser will be almost instantaneous.

2. Writing complex data structures to the database.

Sometimes there are situations when it is not advisable to create another table in the database in order to store various data. Let's say a user registered on the site has the opportunity to customize the background color and text color.

Instead of creating another table for 2 settings, you can simply create a text column in the table with the list of users in which to place the user settings data. Then the settings update request could, for example, be like this:

UPDATE users SET settings = "("background-color":"#FFFFFF", "text-color":"#000000")" WHERE user_id = 10

In the future, having obtained from the table users information, php script can easily turn them back into an array with settings. For example, if the $user_info variable contains data obtained for a user from the users table, getting an array with settings is very simple:

$settings = json_decode($user_info["settings"], true); echo "Background color = ".$settings["background-color"]; echo "Text color = ".$settings["text-color"];

In JSON format, you can also, for example, record in the database which product options the buyer selected.

("15":["45","47"], "18":"52") // option 15 has the values ​​45 and 47 selected, and option 18 has the value 52 selected

In principle, you can even write the entire contents of the cart in JSON format, for example, like this:

( "user_id" : 10, "session_id" : "2c2l3h4ii271aojentejtdcmh3", "products": [ ( "product_id" : 15, "options" : ( "15" : , "18" : 52), "quantity" : 1, "price" : 1500 ), ( "product_id" : 16, "options" : ( "15" : , "18" : 51 ), "quantity" : 2, "price" : 1000 ) ] )

In its usual non-tree form, this JSON string would be like this:

("user_id":10,"session_id":"2c2l3h4ii271aojentejtdcmh3","products":[("product_id":15,"options":("15":,"18":52),,"quantity":1, "price":1500),("product_id":16,"options":("15":,"18":51),,"quantity":2,"price":1000)])

Thus, as can be seen from the examples, almost any information can be stored and transmitted in the JSON format.

Computer