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?
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.
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 exampleBelow 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 XMLIn 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 JavaScriptJSON 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 variableJavaScript 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 PHPPHP, like JavaScript, has built-in functions for working with JSON strings.
Creating a JSON string from a PHP variableThe 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 stringTo 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.
ConclusionAlthough 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:
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 dataThe 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:
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 XMLIn 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 JavaScriptEven 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 variableJavaScript 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 stringThere 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 PHPPHP, 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 variableJson_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 stringSimilar 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 formatIf 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 formatLet'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 formatActually, 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 = "