the Internet Windows Android

JavaScript - JSON and working with it. Introduction to JSON What the JSON TXT file

Ad

JSON WebSite File Format

JSON files are used to store the structures of simple data arrays using a text based format, which can read a person. Initially, the JSON files were closely related to the JavaScript programming language, but due to the fact that this format is currently supporting a large number of software APIs, it can be considered as a format that is not attached to any of the programming languages. This alternative to the XML format is most often used by AJAX web applications.

JSON File Technical Information

JSON files are used as files for data exchange. Such an exchange often occurs between computers connected via the Internet. Thus, very rare files with the JSON extension are saved on the hard disk of the computer. Some applications, however, still use this format. For example, Google+'s profile data is saved and loaded in JSON format, and the Mozilla Firefox web browser uses the files of this format for storing backup bookmarks.

Additional information JSON

The lesson in which is considered what JSON is and which it has advantages compared to other data formats.

Concept json

JSON (JavaScript Object Notation) is a text format of data presentation in the notation of the JavaScript object.

This means that the data in JSON is organized, as well as in the JavaScript object. But unlike the last JSON recording format has some features that will be considered a little later.

JSON is usually used in bundles with AJAX so that the server can pass the data in a convenient form of the JavaScript script, which then appears on the page.

JSON format structure

Who is familiar with the process of creating objects in JavaScript, will not see anything new in the structure of JSON format. This is due to the fact that the JSON structure corresponds to the structure of the JavaScript object with some limitations.

You can easily imagine JSON as a container consisting of elements. Each element in such a container is some structural unit consisting of a key and value.

At the same time, 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 are written as follows:

In the above record, it is clear that the key is separated from the value using the colon sign (:). In this case, the key in the JSON object must be enclosed in double quotes. This is the first JSON feature that distinguishes it from the JavaScript object. Because In the JavaScript object, the key (object property) does not have to be enclosed in double quotes.

For example, the structure of an object that is valid from the point of view of JavaScript and not valid from the point of view of JSON:

Var Person \u003d (Name: "Ivan";) // JavaScript object

Warning: Try the name of the keyword so as not to complicate access to the data, i.e. When you draw up a name, it is preferable to stick to the camel notation or use to connect the Sign of the bottom undercut ("_").

The key value in JSON can be recorded in one of the following formats: String (Line), Number (Number), Object (Object), Array (Array), Boolean (True or False logical value), NULL (Special JavaScript value).

it the second limit in JSON, because JavaScript object may contain any data type, including function.

VAR PERSON \u003d ("NAME": "Ivan"; "setName": function () (Console.log (this.name);)) // JavaScript object

To separate one element (key-value pair) from the other, the comma sign () is used.

For example, consider JSON consisting of various data types.

ATTENTION: JSON data representation format does not allow the use of comments inside its structure.

Work with JSON in JavaScript

Unlike the Javascript object JSON is a string.

For example:

// For example, the Persondata variable contains a string that represents JSON VAR Persondata \u003d "(" Name ":" Ivan "," Age ": 37," Mother ": (" Name ":" Olga "," Age ": 58), "Children": ["Masha", "Igor", "Tanya"], "married": True, "Dog": NULL) ";

JSON work is usually conducted in two directions:

  1. Parsing is a translation of a string containing JSON to the JavaScript object.
  2. Convert JavaScript object in JSON string. In other words, this action performs the conversion of the inverse parsing.

JSON Parser.

JSON Parsing, i.e. Transfer JSON row to JavaScript object is carried out using the EVAL () or PARSE () method.

Using the EVAL () method:

// The Person variable is a JavaScript object, which is obtained by executing code (string) JSON VAR PERSON \u003d EVAL ("(" + Persondata + ")");

Using json.parse () method:

// A variable Person is a JavaScript object, which is received by the JSON Var Person \u003d JSON.Parse string papers (Persondata);

Convert JavaScript object in JSON string

The JavaScript object in the JSON string is carried out using the json.stringify () method. This method performs the reverse method JSON.PARSE ().

Var personstring \u003d json.strigify (person);

Advantages of JSON format

The JSON data representation format has the following advantages:

  • convenient and fast in the work methods intended for conversion (parsing) JSON string to JavaScript object and back;
  • understandable and simple data structure;
  • very small size compared to other data formats (for example, XML). This is due to the fact that the JSON format contains minimal possible formatting, i.e. When it is written, only a few special characters are used. This is a very important advantage, because The data presented in JSON format will be loaded faster than if they were presented in other formats.

Due to the fact that this format has a lot of advantages. It became applied not only in JavaScript, but in many other languages, such as C, Ruby, Perl, Python, PHP, etc.

Comparison of JSON and XML formats

The JSON format has the following advantages over XML format:

  1. When transmitting some data, the JSON size will be significantly less than XML size.
  2. JSON has more convenient conversion methods in JavaScript data structures than XML.
  3. JSON is simple to create than XML.

Work with JSON data after parsing is carried out with the JavaScript object.

// JSON VAR PERSONDATA \u003d "(" Name ":" Ivan "," Age ": 37," Mother ": (" Name ":" Olga "," Age ": 58)," Children ": [" Masha " , Igor, Tanya], "Married": True, "Dog": NULL) "; // JavaScript Object Person Var Person \u003d JSon.Parse (Persondata);

Consider the main points:

// Get the key values \u200b\u200b(properties) Name Person.name; Person ["Name"]; // Get the key values \u200b\u200b(properties) of the Name located in the Mother Person.mother.name object; // Delete Age Delete element // Add (or update) key (property) Person.Eye \u003d "Brown"; // When working with arrays, it is necessary to use methods designed to work with arrays // Delete 1 Element of the array (SPLICE method) Person.Children.splice (1,1) // Add an item to an array (Push method) Person.Children. Push ("Katya");

For burning elements in the object, you can use the for..in cycle:

For (IF (Person.hasownProperty (Key)) (// Key \u003d Key // Value \u003d Person Console.log ("Key \u003d" + Key); console.log ("Value \u003d" + Person) ;) // If the Person object has Key (if Person has a Key property)) // recycle all keys (properties) in the object

For the enormous elements of the array, you can use the following cycle:

For (var i \u003d 0; i

JSON is a text data recording format. It allows in text form to imagine both a separate number or string and complex structures, such as arrays with data. The use of this recording format is convenient because it is readable and intuitively understood, at the same time it allows you to save very complex data structures. In addition, it is more compact than XML, so in my opinion more preferable to exchange data between the web browser and the server.

JSON Syntax on Examples

JSON format is usually written in 2 versions:

1. Sequence of values. For example, a sequence of 10, 15 and "TEST" in JSON format will look like this:

2. recording in the form of steam key: Value . For example:

("FULL NAME": "Ivanov Sergey", "Date of birth": "03/09/1975")

A little 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 with version 5.2. There are only 4 functions:

  • jSON_DECODE. - decodes the JSON string (data from the JSON format row)
  • jSON_ENCODE. - Returns JSON data presentation (converts data to the JSON string)
  • jSON_LAST_ERROR_MSG. - Returns a string with the message about the last call JSON_ENCODE () or JSON_DECODE ()
  • jSON_LAST_ERROR. - Returns the last error

Basically, mostly, only two functions are used: jSON_ENCODE. and jSON_DECODE.. I will not go into the details of their syntax, you can look for more details on php.net. Example of use:

$ arr1 \u003d array (0,1,2); $ json_str \u003d json_encode ($ arr1); Echo $ json_str; // Remove the JSON string: $ ARR2 \u003d JSON_DECODE ($ json_str); Echo $ arr2; // Will out: 1

note : for coding in json-format data in Russian, JSON_ENCODE feature converts Russian characters in unicode. Replaces them on \\ uxxxx. And thus, the JSON line becomes not readable for a person (but understandable for the browser). If you need to transform into Unicode, it does not occur (for example, when debugging code), you can simply use the json_unescaped_unicode option.

Also that when encoding, slaces are not added to shields and that the rows with numbers are encoded as numbers, you can use json_unescaped_slashes and json_numeric_check. As a result, the JSON line will be readable for a person, for example, as follows:

$ arr \u003d array ("fio" \u003d\u003e "Ivanov Sergey", "Age" \u003d\u003e "32", "vk_url" \u003d\u003e "https://vk.com/id11111"); Echo JSON_ENCODE ($ ARR, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

Without using these options, the string would be like this:

("FIO": "\\ u0418 \\ u0432 \\ u0430 \\ u0432 \\ u0421 \\ u0432 \\ u0440 \\ u0433 \\ u0435 \\ u0439", "Age": "32", "vk_url": "https: \\ / \\ And using options, we get a readable string:

("FIO": "Ivanov Sergey", "Age": 32, "vk_url": "https://vk.com/id11111")

Another point: If you want when decoding a JSON row function

JSON_DECODE Returning an array simply add a second parameter to the function equal to TRUE.$ json_str \u003d "(" a ": 1," b ": 2," c ": 3)"; $ OBJ \u003d JSON_DECODE ($ json_str); // We obtain an ECHO $ \u200b\u200bOBJ-\u003e A object; // withdraw 1 $ ARR \u003d JSON_DECODE ($ json_str, true); // We obtain an associative array of Echo $ Arr ["A"]; // Will out 1.

This consideration of PHP functions will complete.

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 just a separate text format used in different languages. Apparently, therefore the JSON syntax is very similar to the syntax of the recording of ordinary objects and arrays.

// An example of an array in JavaScript ARR \u003d; Alert (ARR); // Will out 1 // Example object in JavaScript OBJ \u003d ("Name": "Vasya", "Age": 35, "isadmin": false) alert (obj.name); // Will "Vasya"

JavaScript functions used to convert to JSON format and back:

Json.parse.

  • - decoding JSON string (line transformation in objects and / or arrays) Json.stringify
  • - Returns the JSON view of the data (convert objects and / or arrays in the JSON string)

Simple example of decoding JSON string into an array with numbers:

Str \u003d ""; ARR \u003d JSON.PARSE (STR); Alert (ARR); // Will out 1.

An example of a conversion (serialization) of an object in the JSON string:

OBJ \u003d ("Name": "Vasya", "Age": 35, "isadmin": false) alert (json.stringifying (obj)); // Remove ("Name": "Vasya", "Age": 35, "isadmin": false)

When serialization (transformation) of an object in the JSON string, a 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 an object conversion with the TOJSON method:

OBJ \u003d ("Name": "Vasya", "Age": 35, "isadmin": false, tojson: function () (Return this.age;)) Alert (JSON.Stringify (OBJ)); // Will out 35.

Examples of practical application JSON-format

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

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

For example, we have some kind of page on which you want to update the data without rebooting the page. Suppose it is necessary that the information with the list of employees and their data should be suppressed from the server.

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

$ .getjson ("Get-info.php"). SUCCESS (DATA) (// Ajax request, data from the server will be recorded in the variable DATA HTMLSTR \u003d "

File extension .json.
File category
File example (0.57 KIB)
Related Programs Microsoft Notepad.
Microsoft Wordpad.
NotePad ++.
Mozilla Firefox.
"; for (var i \u003d 0; i "+ Data [i] .fio +""; // First Column - Pho HTMLSTR + \u003d" "; // The second column - the date of birth HTMLSTR + \u003d"";) HTMLSTR \u003d"
"+ Data [i] .birthday +"
"; $ (" div.info "). HTML (HTMLSTR); // in DIV with the Info class we derive the resulting table with data));

On the server, the GET-info.php script to which the AJAX request is made may be, for example, as:

$ user_info \u003d array (); // Create an array with data $ User_info \u003d Array ("FIO" \u003d\u003e "Ivanov Sergey", "Birthday" \u003d\u003e "09.03.1975"); $ user_info \u003d array ("fio" \u003d\u003e "Petrov Aleksey", "Birthday" \u003d\u003e "09/18/1983"); echo json_encode ($ user_info); exit;

In this example, the JSON string, which was transferred from the server to the browser was like this:

[("FIO": "Ivanov Sergey", "Birthday": "03/09/1975"), ("fio": "Petrov Aleksey", "Birthday": "09/18/1983")]

I specifically did not show a string in the form of "tree", because It is transmitted in this form. And how can you appreciate data record in JSON format turned out to be very compactThis means that the transfer of this data from the server to the browser will be practically instantaneous.

2. Record complex data structures to the database.

Sometimes there are situations where it is not advisable to start the table in the database to save various data. Suppose, assume that the user registered on the site has the ability to make the text color and text color setting.

Instead of starting another table for the sake of 2 settings, it is possible to make a text column in the table with a list of users to make the user settings data. Then the settings update request may, for example, be:

Update Users Settings \u003d "(" Background-Color ":" # FFFFFF "," Text-Color ":" # 000000 ")" WHERE User_ID \u003d 10

In the future, receiving 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 the data obtained by the user from the USERS table, get an array with the settings is very simple:

$ settings \u003d json_decode ($ User_info ["Settings"], TRUE); Echo "Background color \u003d". $ settings ["Background-Color"]; echo "Text color \u003d". $ settings ["Text-Color"];

In JSON format, you can also, for example, write to the database what options of goods chose the buyer.

("15": ["45", "47"], "18": "52") // Option 15 The values \u200b\u200bof 45 and 47 are selected, and the option 18 is selected 52

In principle, you can even write all the contents of the basket in JSON format, for example, as follows:

("user_id": 10, "session_id": "2C2L3H4II271AOOJENTEJTDCMH3", "Products": [("Product_ID": 15, "Options": (15 ":," 18 ": 52)," quantity ": 1, "Price": 1500), ("Product_id": 16, "Options": ("15":, "18": 51), "quantity": 2, "Price": 1000)]

In the usual not tree form, this json line will be like this:

("user_id": 10, "session_id": "2c2l3h4i271aojentejtdcmh3", "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 seen from examples, you can store and transmit virtually any information in JSON format.

JSon. JavaScript Object Notation is a simple data exchange format, convenient for reading and writing both both a person and a computer. It is based on a subset of the JavaScript programming language defined in ECMA-262 3RD Edition - December 1999. JSON is a text format, fully independent of the implementation language, but it uses agreements familiar with C-similar languages, such as C, C ++, C #, Java, JavaScript, Perl, Python and many others. These properties make JSON the ideal data logging language.

JSON is based on two data structures:

  • Collection of pair key / value. In different languages, this concept is implemented as an object, recording, structure, dictionary, hash, named list or associative array.
  • Ordered list of values. In most languages \u200b\u200bit is implemented as array, vector, list or sequence.

These are universal data structures. Almost all modern programming languages \u200b\u200bsupport them in any form. It is logical to assume that the data format, independent of the programming language, should be based on these structures.

In the notation JSON it looks like this:

An object - Disordered set of pair key / value. The object begins with (opening brace and ends) with a closing curly bracket. Each name is accompanied by: colon, pairs of key / value are separated, comma.

Array - ordered collection of values. The array begins with [the opening square bracket and ends] with a closing square bracket. Values \u200b\u200bare separated, comma.


Value may be line in double quotes number, TRUE, FALSE, NULL, object or an array. These structures can be invested.


Line - Collection of scratch or more Unicode characters enclosed in double quotes using \\ reverse oblique line as a screening symbol. The symbol is represented as a single-spray string. Similar syntax is used in C and Java.


Number It seems the same as in C or Java, except that the decimal number is used.


Spaces can be used between any lexemes.

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


Familiar with programming people immediately recognize files with JSON extension. This format is an abbreviation of the terms JavaScript Object Notation, and it is essentially a text-based data exchange option used in the JavaScript programming language. Accordingly, cope with the opening of such files will help either specialized software or text editors.

The main feature of the scripts in JSON format is the interchangeability of it to XML format. Both types are text documents that can be opened with text processors. However, we start with a specialized software.

Method 1: Altova XMLSPY

A sufficiently well-known development environment that the web programmers are used. This environment also generates JSON files, therefore is capable of opening third-party documents with such an extension.


The disadvantages of this two. The first is a paid proliferation basis. The trial version is active 30 days, however, it is necessary to specify the name and mailbox. The second is the total bulky: a person who just needs to open the file, it may seem too faded.

Method 2: NotePad ++

NotePad ++ multifunctional text editor - first of the list suitable for opening scripts in JSON format.


Pluses NotePad ++ is pretty - here and displaying the syntax of many programming languages, and support plugins, and small size ... However, due to some features, the program works leisurely, especially if you open a voluminous document in it.

Method 3: Akelpad

Incredibly simple and at the same time, a rich text editor from the Russian developer. The number supported by them includes JSON.


Like Notepad ++, this option notepad is also free and supports plugins. It works freeze, but large and sophisticated files may not open the first time, so keep in mind such a feature.

Method 4: Komodo Edit

Free software for writing program code from Komodo. Different with modern interface and wide support for functions for programmers.


In the program, unfortunately, there is no Russian language. However, the ordinary user will rather scare up excess functional and incomprehensible interface elements - after all, this editor is focused primarily on programmers.

Method 5: Sublime Text

Another representative of Code-Oriented text editors. The interface is easier than colleagues, however the capabilities are the same. A portable version of the application is available.


Unfortunately, Sublime Text is not available in Russian. The disadvantage can also be called a conditionally free model of distribution: the free version is not limited by anything, but from time to time a reminder appears about the need to purchase a license.

Method 6: nfopad

Simple notebook, however, to view documents with the extension of JSON will also fit.