• json description. JavaScript - JSON and methods for working with it. A simple example of JSON data

    JSON is a text format for writing data. It allows you to present in text form both a single number or a 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 it allows you to save very complex data structures. Also, it is more compact than xml, so in my opinion it is more preferable for data exchange between web browser and server.

    JSON Syntax with Examples

    The json format is usually written in 2 versions:

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

    2. Recording in the form of key:value pairs. For example:

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

    A slightly more complex example:

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

    PHP functions for working with JSON format

    In php language since 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 with 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 will not go into the 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; // output json string: $arr2 = json_decode($json_str); echo $arr2; // output: 1

    Please note: when encoding data in JSON 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 don't want to convert to Unicode (for example, when debugging code), you can simply use the JSON_UNESCAPED_UNICODE option.

    You can also use JSON_UNESCAPED_SLASHES and JSON_NUMERIC_CHECK to avoid adding slashes for escaping during encoding and to encode strings with numbers as numbers. As a result, in order for the json string to be human-readable, we will do, for example, like 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 these options, the line would be:

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

    and using options, we get a readable string:

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

    One more thing: if you want the json_decode function to return exactly an array when decoding a json string, just add the second parameter to the function equal to true.

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

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

    // JavaScript array example arr = ; alert(arr); // displays 1 // An example of an object in JavaScript obj = ( "name": "Vasya", "age": 35, "isAdmin": false ) alert(obj.name); // displays "Vasya"

    JavaScript functions used to convert to and from JSON format:

    • JSON.parse - decoding a JSON string (converting a string to objects and/or arrays)
    • JSON.stringify - returns a JSON representation of the 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); // prints 1

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

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

    When serializing (converting) an object to a JSON string, the object's toJSON method is called, 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)); // prints 35

    Examples of practical use of the JSON format

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

    1. Data transfer between browser and server using Ajax requests.

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

    In JavaScript, using jQuery, we 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 "Ivanov Sergey", "birthday" => "03/09/1975"); $user_info = array ("fio" => "Aleksey 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:

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

    I deliberately did not show the line in the form of a "tree", because it is transmitted in this form. And as you can appreciate, writing JSON data is 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 start another table in the database in order to store different data. Let's say, let's say that a user registered on the site has the opportunity to make settings for the background color and text color.

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

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

    In the future, having received information from the users table, the php script can easily turn them back into an array with settings. For example, if the $user_info variable contains data retrieved 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, write to the database which product options the buyer has chosen.

    ("15":["45","47"], "18":"52") // option 15 is set to 45 and 47, and option 18 is set to 52

    In principle, you can even write the entire contents of the basket 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 a normal non-tree view, this JSON string would look 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 you can see from the examples, almost any information can be stored and transmitted in JSON format.

    You must have heard of JSON before. What is it? What can it do and how can it be used?

    In this lesson, we will cover the basics of JSON and cover the following points:

    • What is JSON?
    • What is JSON used for?
    • How to create a JSON string?
    • A simple JSON string example.
    • Let's compare JSON and XML.
    • How to work with JSON in JavaScript and PHP?
    What is JSON?

    JSON is a simple, text-based way to store and communicate structured data. With a simple syntax, you can easily store anything from a single number to strings, arrays, and objects in plain text. You can also link arrays and objects together to create complex data structures.

    Once a JSON string has been created, it's easy to send it to another application or to another location on the network because it's plain text.

    JSON has the following benefits:

    • It is compact.
    • Its sentences are easy to read and compose by both human and computer.
    • It can be easily converted to a data structure for most programming languages ​​(numbers, strings, booleans, arrays, and so on)
    • Many programming languages ​​have functions and libraries for reading and creating JSON structures.

    The name JSON stands for JavaScript Object Notation (representation of JavaScript objects). As the name represents, it is based on the way objects are defined (very similar to creating associative arrays in other languages) and arrays.

    What is JSON used for?

    The most common common use of JSON is to send data from the server to the browser. Typically, JSON data is delivered using AJAX , which allows the browser and server to exchange data without having to reload the page.

  • The user clicks on a product thumbnail in an online store.
  • The JavaScript running on the browser makes an AJAX request to the PHP script running on the server, passing in the ID of the selected product.
  • The PHP script gets the product name, description, price and other information from the database. It then composes a JSON string from the data and sends it to the browser.
  • The JavaScript running on the browser receives the JSON string, decodes it, and displays the product information on the page for the user.
  • You can also use JSON to send data from the browser to the server by passing the JSON string as a parameter in GET or POST requests. But this method is less common, as passing data through AJAX requests can be simplified. For example, the product ID may be included in the URL as part of the GET request.

    The jQuery library has several methods, such as getJSON() and parseJSON() , that make it easy to retrieve data using JSON through AJAX requests.

    How to create a JSON string?

    There are a few basic rules for creating a JSON string:

    • The JSON string contains either an array of values ​​or an object (an associative array of name/value pairs).
    • array is enclosed in square brackets ([ and ]) and contains a comma-separated list of values.
    • An object is enclosed in curly braces (( and )) and contains a comma-separated list of name/value pairs.
    • name/value pair consists of the field name enclosed in double quotes, followed by a colon (:) and the field value.
    • Meaning in an array or object can be:
      • Number (integer or floating point)
      • String (in double quotes)
      • Boolean value (true or false)
      • Another array (enclosed in square brackets)
      • Another object (enclosed in curly braces)
      • null value

    To include double quotes in a string, you need to use a backslash: \" . Just like in many programming languages, you can put control characters and hex codes in a string by preceding them with a backslash. See the JSON site for details.

    Simple JSON String Example

    The following is an example of a checkout in JSON format:

    ( "orderID": 12345, "shopperName": "Vanya Ivanov", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "Super product", "quantity": 1 ), ( "productID": 56, "productName": "Miracle product", "quantity": 3 ) ], "orderCompleted": true )

    Let's look at the line in detail:

    • We create an object using curly braces (( and )).
    • There are several name/value pairs in the object: "orderID": 12345 Property with name "orderId" and integer value 12345 "shopperName": "Vanya Ivanov" property with name "shopperName" and string value "Vanya Ivanov" "shopperEmail": " [email protected]" Property named "shopperEmail" with string value " [email protected]" "contents": [ ... ] Property named "contents" whose value is an array "orderCompleted": true Property named "orderCompleted" with boolean value true
    • There are 2 objects in the "contents" array representing the line items in the order. Each object contains 3 properties: productID , productName , and quantity .

    By the way, since JSON is based on declaring JavaScript objects, you can quickly and easily make the above JSON string a JavaScript object:

    var cart = ( "orderID": 12345, "shopperName": "Vanya Ivanov", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "Super product", "quantity": 1 ), ( "productID": 56, "productName": "Miracle product", "quantity": 3 ) ], "orderCompleted": true );

    Comparing JSON and XML

    In many ways, you can consider JSON as an alternative to XML, at least in the realm of web applications. The concept of AJAX was originally based on the use of XML to transfer data between a server and a browser. But in recent years, JSON has become more and more popular for AJAX data transfer.

    While XML is a proven technology that has been used in a fair number of applications, JSON has the advantage of being a more compact and easier-to-recognise data format.

    Here is how the above XML object example would look like:

    orderID 12345 shopperName Vanya Ivanov shopperEmail [email protected] contents productID 34 productName Super Product quantity 1 productID 56 productName Super Product quantity 3 orderCompleted true

    The XML version is significantly larger. It is actually 1128 characters long, while the JSON variant is only 323 characters long. The XML version is also hard to understand.

    Of course, this is a radical example. And it is possible to create a more compact XML entry. But even it will be significantly longer than the JSON equivalent.

    Working with JSON string in JavaScript

    JSON has a simple format, but manually creating a JSON string is quite tedious. In addition, you often need to take a JSON string, convert its contents into a variable that can be used in code.

    Most programming languages ​​have tools to easily convert variables to JSON strings and vice versa.

    Create a JSON string from a variable

    JavaScript has a built-in JSON.stringify() method that takes a variable and returns a JSON string representing its contents. For example, let's create a JavaScript object that contains the order details from our example, and then create a JSON string from it:

    var cart = ( "orderID": 12345, "shopperName": "Vanya Ivanov", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "Super product", "quantity": 1 ), ( "productID": 56, "productName": "Miracle product", "quantity": 3 ) ], "orderCompleted": true ); alert(JSON.stringify(cart));

    This code will give:

    Note that the JSON.stringify() method returns a JSON string without spaces. It's harder to read, but it's more compact for transmission over a network.

    There are several ways to parse a JSON string in JavaScript, but the safest and most reliable is to use the built-in JSON.parse() method. It takes a JSON string and returns a JavaScript object or array that contains the data. For example:

    var jsonString = " \ ( \ "orderID": 12345, \ "shopperName": "Vanya Ivanov", \ "shopperEmail": " [email protected]", \ "contents": [ \ ( \ "productID": 34, \ "productName": "Super Product", \ "quantity": 1 \ ), \ ( \ "productID": 56, \ "productName": "Wonder Product", \ "quantity": 3 \ ) \ ], \ "orderCompleted": true \ ) \ "; var cart = JSON.parse(jsonString); alert(cart.shopperEmail); alert(cart.contents.productName);

    We have created a jsonString variable that contains the JSON string of our order example. We then pass this string to the JSON.parse() method, which creates an object containing the JSON data and stores it in the cart variable. All that's left to do is test by printing out the properties of the shopperEmail object and the productName of the contents array.

    As a result, we will get the following output:

    In a real application, your JavaScript code will receive the order as a JSON string in an AJAX response from the server script, pass the string to the JSON.parse() method, and then use the data to display it on the user's page.

    JSON.stringify() and JSON.parse() have other capabilities, such as using callback functions to custom convert certain data. These options are very handy for converting various data into valid JavaScript objects.

    Working with JSON string in PHP

    PHP, like JavaScript, has built-in functions for working with JSON strings.

    Create a JSON string from a PHP variable

    The json_encode() function takes a PHP variable and returns a JSON string representing the content of the variable. Here is our order example written in PHP:

    This code returns exactly the same JSON string as in the JavaScript example:

    ("orderID":12345,"shopperName":"Vanya Ivanov","shopperEmail":" [email protected]","contents":[("productID":34,"productName":"Super Product","quantity":1),("productID":56,"productName":"Wonder Product","quantity": 3)],"orderCompleted":true)

    In a real application, your PHP script will send this JSON string as part of an AJAX response to the browser, where the JavaScript code, using the JSON.parse() method, will parse it back into a variable to display on the user's page.

    You can pass various flags as the second argument to the json_encode() function. With their help, you can change the principles of encoding the contents of variables into a JSON string.

    Create a variable from a JSON string

    The json_decode() method is used to convert a JSON string into a PHP variable. Let's replace our JavaScript example with the JSON.parse() method with PHP code:

    As for JavaScript, this code will produce:

    [email protected] miracle goods

    By default, the json_decode() function returns JSON objects as PHP objects. There are generic PHP objects of class stdClass . That's why we use -> to access the properties of the object in the example above.

    If you need a JSON object in the form of an associated PHP array, you must pass true as the second argument to the json_decode() function. For example:

    $cart = json_decode($jsonString, true); echo $cart["shopperEmail"] . "
    "; echo $cart["contents"]["productName"] . "
    ";

    This code will produce the same output:

    [email protected] miracle goods

    You can also pass other arguments to the json_decode() function to specify the depth of recursion and how large integers are handled.

    Conclusion

    While JSON is easy to understand and use, it is a very useful and flexible tool for passing data between applications and computers, especially when using AJAX. If you are planning to develop an AJAX application, then there is no doubt that JSON will be the most important tool in your workshop.

    JSON (JavaScript Object Notation) is a simple data interchange format that is easy to read and write by both humans and computers. It is based on a subset of the JavaScript programming language, as defined in the ECMA-262 3rd Edition - December 1999 standard. JSON is a text format that is completely independent of the implementation language, but 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 exchange language.

    JSON is based on two data structures:

    • 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 generic data structures. Almost all modern programming languages ​​support them in some form. It is logical to assume that the data format, independent of the programming language, should be based on these structures.

    In JSON notation, it looks like this:

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

    array- an ordered collection of values. An array starts with a [ opening square bracket and ends with a ] closing square bracket. Values ​​are separated by a comma.


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


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


    Number 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.

    Except for some coding details, the above describes the language in its entirety.


    Variables, arrays and objects are a familiar and convenient form of data representation. It is customary to describe data in the JavaScript browser language, which is not necessary in the PHP server language. The JSON format allows you to generalize them into one whole and not to focus on the programming language. In this case, the data is converted into pairs: "name = value". The value in each of them can also be a collection of such pairs.

    It is customary to associate JSON with curly braces, and the latter is quite justified, since the JSON = Object Notation JavaScript format. Much has changed in recent particularly dynamic years. What was created for a specific purpose often brought unexpected results or opened up new horizons.

    Data exchange: browser - server

    AJAX technology has become traditional, the usual page refresh entirely ceased to be popular. The visitor, opening the site, initiates a series of partial data exchanges, when certain pages change only in the place that is relevant.

    It is believed that the appearance of JSON is associated with the use of AJAX, but in fact, associative and its object notation (features of the syntax for describing and using objects) are much more related to JSON than data exchange between the browser and the server.

    Since the content of the pages of modern sites has really become “massive” (volumetric), the efficiency of the format for data exchange has become of particular importance. This is not to say that JSON has become a new representation of data, but the fact that it has long been a JavaScript syntax element is significant.

    Using Cyrillic in naming variables is a very unexpected phenomenon (nonsense), but it works in the latest versions of Chrome, Firefox and even Internet Explorer 11.

    Cyrillic and JSON

    Of course, you should not use this completely unexpected phenomenon, remembering how easily the values ​​​​of variables written in Russian letters turn into krakozyabry: what can we say about names, especially external ones.

    It is doubtful that the initiative in Cyrillic names will be supported by the browser's external environment, with which it constantly has to deal. But this fact deserves attention for the simple reason that the JSON format is the ability to write names and values ​​in any way the developer wants. This is important, since in each problem the description of the scope as it requires it greatly simplifies debugging and reduces the number of errors.

    It doesn't matter what the syntactic innovation was based on - JSON, it is important that it gave a legal right and a real opportunity to match: "any name = any value".

    We must pay tribute to the JavaScript language: what is provided by the syntax does not oblige the developer and does not impose anything on him. The developer freely uses the syntax of the language for the optimal formation of the data model and the algorithm for their use.

    PHP and JSON

    Accepting data in JSON format, the server (via PHP, in particular) provides the ability to process them as is and return the result back to the browser in a similar format. PHP Source Array:

    • $cJSON = array ("a"=> "alfa", "b"=> "beta", "g"=> "gamma").

    Converting to JSON format for passing to the browser:

    • $cJS = json_encode($cJSON).

    Result:

    • ("a":"alfa","b":"beta","g":"gamma").

    The nesting shown in the photo is allowed.

    Here, the formed array has been added with a new element "into itself" with automatic index "0" and then again with the specified index "z".

    Json_decode() converts a JSON string into a PHP array. Similar results can be achieved by manipulating functions and explode(). In some cases, this option is preferable.

    nesting level

    Elements can be nested within each other both on the browser side and on the server side. In practice, the JSON format (described by RFC 4627) provides well over 4 levels of nesting, but this capability should not be abused.

    It's best to never go beyond reasonable sufficiency, it makes the code readable and makes it easier to debug and understand for other developers.

    JSON is usually referred to as data structures that are simpler than XML, understandable to both humans and computers. This is true when the amount of data is small, and the developer has chosen the nesting level correctly. In all other cases, it is difficult to count the number of brackets and understand both on the browser side and on the server side.

    JSON files

    The use of JSON in practice is often not limited to a short string accessible to perception. Any data constructions are always pragmatic. At the same time, JSON can be effectively used both in the real task data (enterprise staff) and for the implementation of temporary data (object cache).

    Enterprise State and JSON Format: An Example

    Usually a record about one person is a surname, name, patronymic, year of birth, specialty, education, ... and a few more simple values. Even in particularly demanding companies, a record about one person will not exceed a dozen or two fields. This is perceptual and can be placed in a database row.

    If a company employs several people, this is one thing, but if tens of thousands, this is quite another. You can continue to use the database, but storing it as a file looks more practical and easier to use.

    JSON is a plain text file. The case with the staffing, all right. You can always read it. Open and edit is also available in any text editor that does not have the habit of adding its service information to the file content. In general, *.json is pure text both inside the browser and inside the file - a string.

    The photo shows the cache of the object that forms the picture, an example.

    This is an example of the contents of a file generated by a website that provides color 3D printing on mugs and ceramics. Naturally, having such a JSON format, deciding how to open it is really problematic. However, in this and similar cases, there is no problem reading the file: PHP reads the file, parses it, and passes it to the browser. The data changed by the visitor is returned to the server and written back.

    In this use case, the file acts as a variable that is stored outside the code. If necessary, the variable receives a value from the file, and if it is changed by the visitor in the dialog provided by the site, then all changes will be recorded as is. There is no need to read and check the contents of the file.

    JSON is often used to store and use service information - this is not a staffing table, neither the developer nor the site visitor needs to see it.

    XML and JSON

    "There is a time for everything" is a classic knowledge, accepted as an axiom even before the advent of programming. "Nothing appears just like that" - this was also before man wrote the first intelligible program in an artificial language.

    Data formats emerge from a real need and are based on the knowledge gained. HTML has its own way, XML has its own way, and JSON is JavaScript object logic extended to other languages. Comparing one to the other is not the best thing to do. To each his own.

    XML copes wonderfully with its tasks and is clearly not going to go down in history. And JSON was used until 2006, just not every developer considered it his duty to declare certain options for presenting his data.

    There have been cases in practice when programs were written in BASIC that did not use JSON as such, but perfectly stored name = value pairs and made them available to the right algorithms at the right time.

    Special characters ("`", "~", "|", ...) and data formats

    The habit of working with associative arrays and objects in JavaScript makes using JSON natural and convenient. This is indeed a great format, but the ability to split and join, manipulating strings and arrays, has much deeper roots.

    JavaScript's join/split and PHP's implode/explode functions allow you to conveniently and efficiently use both XML and JSON data formats, as well as your own version. The latter is often better, while the former two are ideal for general use cases. If information is being transferred to another developer, server, file or database, XML and JSON are better not to be found. Everyone works with them, so the transmission / reception of information does not need comments.

    Using JSON in Android

    Reading and writing data in JSON format in Android is not only the norm, but there are many objects that are oriented to work with this particular data format.

    It uses the JSON format. Perhaps this is true, but the question is not in the phenomenality of social networks, but in the fact that the presentation of information in the "name = value" format is really convenient both for programming and for use. Unlike the strict and notorious “XML”, this is a really human-friendly format.

    Associative arrays

    It so happened that variables should be described (JavaScript) or at least indicate the initial value (PHP). In both cases, the variable can change its type very easily. The language performs this transformation automatically if necessary.

    But why shouldn't the variable also change its name, appear during the execution of the algorithm, and disappear when it is no longer needed? Associative arrays solve this problem, but then when such relatively dynamic variables are used, the array name and associated syntax constructs will follow where they are applied.

    This circumstance is especially pronounced in PHP, but you can put up with this, as, however, with the “$” symbol in the variable name and the “$this->” combination inside the object. Programming at the same time in JavaScript and PHP, at first you really wonder how everything is different, but then everything becomes so familiar and natural...

    Associative Array -> JSON

    In this example, a *.docx document is created using the PHPOffice/PHPWord library, and the aProperties array contains the document's properties (author, company, title, category, creation date...).

    The second array contains page data:

    • orientation (landscape or normal);
    • dimensions vertically and horizontally;
    • padding (left, top, bottom, right margins);
    • headers and footers.

    The document is generated on the server where the PHPOffice/PHPWord library is installed. The site provides for managing the values ​​of these arrays using JavaScript. The result in JSON format is returned back to the server and used in PHP algorithms, in its constructions, that is, in arrays.

    Dynamic variables

    The JSON format solves the problem of dynamic variables. Here you can create, modify and delete variables without unnecessary syntactic clutter. It looks nice and is used in JavaScript.

    In this example, the GetOjInfo() function fetches the value name and value from the object. Initially, the JSON string object assigned to the ojInfo variable has three elements: Name, age, and work. A little later, the Status variable is added.

    After the first delete statement, the ojInfo line loses the age element, after the second delete - the work element. If we assume that this line is a collection of variables that have a certain meaning, then using JSON you can actually create, change and delete any of their sets outside the operational field (syntax) of the description and processing of the JavaScript language.

    The JSON format was not designed for this option, but this is possible, practical and convenient.

    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.

    The 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. JavaScript names are not.

    JSON values

    JSON values ​​can be:

    • Series (integer or float)
    • String (in double quotes)
    • Boolean (true or false)
    • Array (in square brackets)
    • Object (in curly brackets)
    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 is a record of a person (with first and last name).

    JSON uses JavaScript Syntax

    Because the JSON syntax is derived from the JavaScript object notation, very little additional software is needed to work 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 in an array of JavaScript objects can be accessed like this:

    Also, you can get it like this:

    The data can be changed as follows:

    It can also be changed like this:

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

    JSON files
    • File type for JSON files ".json"
    • MIME type for JSON text "application/json"