Computers and modern gadgets

A lesson that looks at what JSON is and what advantages it has over other data formats.

Understanding JSON

JSON (JavaScript Object Notation) is a text format for representing data in JavaScript object notation.

This means that the data in JSON is organized in the same way as in a JavaScript object. But unlike the latter, the JSON recording format has some features that will be discussed a little later.

JSON is usually used in conjunction with AJAX so that the server can pass data in a convenient form to a JavaScript script, which will then display it on the page.

JSON Format Structure

Those who are familiar with the process of creating objects in JavaScript will not see anything new in the structure of the JSON format. This is because the JSON structure matches the JavaScript object structure with some restrictions.

It's easier to think of JSON as a container of elements. Each element in such a container is some structural unit consisting of a key and a value.

In this case, the value is directly related to the key and form the so-called key-value pair. In order to get a value in such an object, you need to know its key. Syntactically, such data in JSON is written as follows:

In the above entry, you can see that the key is separated from the value with a colon (:). In this case, the key in the JSON object must be enclosed in double quotes. This is the first feature of JSON that distinguishes it from a JavaScript object. Because in a JavaScript object, the key (object property) does not need to be enclosed in double quotes.

For example, an object structure that is valid from a JavaScript perspective but not valid from a JSON perspective:

Var person = ( name: "John"; ) // JavaScript object

Warning: try to set the key name in such a way as not to complicate data access, i.e. when composing a name, it is preferable to use camel case notation or use an underscore ("_") to connect words.

The key value in JSON can be written in one of the following formats: string (string), number (number), object (object), array (array), boolean (boolean value true or false), null (JavaScript special value).

This is the second limitation in JSON, because a JavaScript object can contain any type of data, including a function.

Var person = ( "name" : "John"; "setName": function() ( console.log(this.name); ) ) // JavaScript object

A comma (,) is used to separate one element (key-value pair) from another.

For example, consider a JSON consisting of various data types.

Attention: the JSON data representation format does not allow the use of comments within its structure.

Working with JSON in JavaScript

Unlike a JavaScript object, JSON is a string.

For example:

// for example, the personData variable contains a string that is JSON var personData = "("name":"Ivan","age":37,"mother":("name":"Olga","age": 58),"children":["Masha","Igor","Tanya"],"married": true,"dog": null)";

Working with JSON is usually carried out in two directions:

  • Parsing is the translation of a string containing JSON into a JavaScript object.
  • Converting a JavaScript object to a JSON string. In other words, this action does the reverse of parsing.
  • Parsing JSON

    JSON parsing, i.e. translating a JSON string into a JavaScript object is done using the eval() or parse() method.

    Using the eval() method:

    // the person variable is a JavaScript object that is obtained by executing the JSON code (string) var person= eval("("+personData+")");

    Using the JSON.parse() method:

    // the person variable is a JavaScript object that is obtained by parsing a JSON string var person = JSON.parse(personData);

    Converting a JavaScript Object to a JSON String

    Translating a JavaScript object into a JSON string is done using the JSON.stringify() method. This method does the opposite of the JSON.parse() method.

    Var personString = JSON.strigify(person);

    Benefits of the JSON format

    The JSON data representation format has the following advantages:

    • convenient and fast methods for converting (parsing) a JSON string into a JavaScript object and vice versa;
    • clear and simple data structure;
    • very small size compared to other data formats (eg XML). This is because the JSON format contains the minimum possible formatting, i.e. when writing it, only a few special characters are used. This is a very important advantage, because data presented in JSON format will load faster than if it were presented in other formats.

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

    Comparison of JSON and XML formats

    The JSON format has the following advantages over the XML format:

  • When passing some data, the JSON size will be significantly smaller than the XML size.
  • JSON has more convenient methods for converting to JavaScript data structures than XML.
  • JSON is easier to create than XML.
  • Working with JSON data after parsing is done as with a JavaScript object.

    //JSON var personData = "("name":"Ivan","age":37,"mother":("name":"Olga","age":58),"children":["Masha" ,"Igor","Tanya"],"married": true,"dog": null)"; //JavaScript person object var person = JSON.parse(personData);

    Consider the main points:

    //get the values ​​of the key (property) name person.name; person["name"]; //get the values ​​of the key (property) name, located in the object mother person.mother.name; //delete age element delete(person.age) //add (or update) key (property) person.eye = "brown"; //when working with arrays, you must use methods designed to work specifically with arrays //remove 1 element from the array (splice method) person.children.splice(1,1) //add an element to the array (push method) person.children. push("Kate");

    To iterate over the elements in an object, you can use a for..in loop:

    For (key in person) ( if (person.hasOwnProperty(key)) ( //key = key //value = person console.log("Key = " + key); console.log("Value = " + person) ; ) // if the person object has a key (if person has a key property) ) // iterate over all keys (properties) in the object

    You can use the following loop to iterate over the elements of an array:

    For (var i=0; i

    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 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":"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 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 a web server and a client or browser.

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

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

    JSON syntax and structure

    The JSON object is in the form of a key-value 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 a 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 multiple strings.

    As you can see, the object consists of key-value pairs, which are enclosed in curly braces. Most of the data in JSON is written as objects.

    A colon is placed between the key and value. Each pair must be followed by a comma. The result is:

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

    The key in JSON is on the left. The key must be enclosed 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 when programming, there may be 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 (such as objects or JSON arrays).

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

    As a rule, data in .json files is written in a column, but JSON can also be written in a line:

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

    This is how JSON data is usually written to another type of file.

    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 split data into a human-readable 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 transferred quickly.

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

    Complex types in JSON

    JSON can store nested objects and arrays that 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 data about users. For each user

    ("john", "jesse", "drew", "jamie") as a value, a nested object is passed, 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 nested and main objects. Commas are used in nested objects in the same way as in ordinary ones.

    Nested arrays

    Data can be embedded 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 data of various types.

    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 given 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 convenient for human and machine perception. 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, hence the files are larger and more difficult to read and write. Moreover, XML is only processed with an XML interpreter, while JSON can be processed with a simple function. Unlike JSON, XML cannot store arrays.

    Let's compare two files: they contain the same data, but the first one is written in XML format and the second one is written 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 doesn't require as many tags as XML. Also, 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 (specifically in terms of tags). JSON is simpler, requires less text, and is easier to use in, for example, AJAX applications.

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

    JSON Tools

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

    More information about JSON compatibility and handling can be found on the project site and in the jQuery library.

    It's rare to write JSON from scratch. Typically, data is loaded from sources or converted to JSON. You can convert CSV or tab-delimited data to JSON using 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 result.

    JSON files (including converted data) can be validated 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.

    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"

    What is JSON and what is it capable of? In this article, you will learn how to use JSON to work with data easily. 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 to use it?

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

    • What is JSON format?
    • How to create JSON strings?
    • A simple example of JSON data
    • Comparing JSON to XML

    Let's start!

    What is JSON format?

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

    After creating a JSON string, it can be easily sent to any application or computer, as it is just text.

    JSON has many advantages:

    • It is compact
    • It is human-readable and easy to read by computer.
    • It can be easily converted to programmatic 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, JSON stands for JavaScript Object Notation. As described earlier, this format is based on object creation, somewhat similar to associative arrays in other programming languages.

    What is the purpose of JSON?

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

    How it looks like in the example:

  • User clicks on thumbnail image
  • JavaScript handles this event and sends an ajax request to the PHP script, passing in the ID of the image.
  • On the server, php gets the description of the image, the name of the image, the address of the large image, and other information from the database. Upon receipt, it converts to JSON format and sends it back to the user's page.
  • JavaScript receives the JSON response, processes the data, generates html code, and displays a larger 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 getJSON() and parseJSON() functions that help you work with the format through ajax requests.

    How to create JSON strings?


    The following 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 ], may contain a list of values ​​that are separated by a coma.
    • Objects wrapped with curly shackles, ( 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 given field.
    • Values ​​in an array or object can be:
      • Numeric (integer or fractional with a dot)
      • Strings (wrapped in double quotes)
      • Boolean (true or false)
      • Other arrays (wrapped in square brackets [ and ])
      • Other objects (wrapped in shaped arms ( and ))
      • Null value (null)

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

    A 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 bows ( and ), which 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": "[email protected]" - just like in the previous field, the buyer's email is stored here.
  • "contents": [ ... ] is a field named content, the value of which is an array.
  • "orderCompleted": true - 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 to XML

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

    While 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 long. Also the XML version is harder to read.

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

    How to work with JSON through PHP and JS?

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

    Creating and reading JSON format with JavaScript


    Although the JSON format is simple, it is difficult to write it by hand 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:

    Creating 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, run the string through a function that creates variables containing the data.

    Let's see how this is done in JavaScript.

    Create a JSON string from a JavaScript variable

    JavaScript has a built-in method, JSON.stringify() , that takes a javascript variable and returns a json string representing the contents of the variable. For example, let's use the previously created object, 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));

    Here is what will be displayed 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. Difficult to read, but more compact, which is important when transferring data.

    Create JavaScript variable from JSON string

    There are several ways to parse JSON strings, the most acceptable and safest is using the JSON.parse() method. It takes a JSON string and returns a JavaScript object or array containing the JSON data. Here is 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 have created a variable, jsonString, which contains the JSON string from the previously provided examples. Then we passed this line through JSON.parse() to create an object containing JSON data, which is stored in the cart variable. Finally, we check for the presence of data and display some information using the modal alert window.

    The following information will be displayed:

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

    Creating and reading JSON format with PHP


    PHP, like JavaScript, has functions that allow you to convert variables to JSON format, and vice versa. Let's take a 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 "cart" written in PHP:

    This code outputs 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] Wonder Widget

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

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

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

    This produces the same result:

    [email protected] Wonder Widget

    Also, additional arguments can be passed to the json_decode () function to determine the processing of large numbers and recursion.

    In conclusion about JSON format

    If you are going to create a web application using Ajax technology, definitely use the JSON format to exchange data between the server and the browser.


    If you notice an error, select a piece of text and press Ctrl + Enter
    SHARE:
    Computers and modern gadgets