Json was created for JavaScript (its full name is JavaScript Object Notation), and it is a data exchange format.

Json has found its use in various programming languages ​​- for example, in PHP, where it looks like this:

["1":"yellow";"2":"green";"3":"grey"]

The example shows that there are no spaces, and the name and value are enclosed in double quotes. If the length allows, the string can be used to transfer data in the GET method.

In this case, the transmitted array can have a multi-level structure. PHP has a set of json functions designed to create and decode such strings and work exclusively with UTF-8.

Json_encode in php This function converts an object, array or variable into json format. The following example will convert an array to this format. ?> Json_decode in php This function decodes the received string and depending on which option was selected we get an object or an array. The function has two parameters - mandatory (a string to be decrypted) and optional (if you specify it, an array will be output, if not, an object). Consider the following example. Getting data from a class: Getting data from an array: Json_last_error in php

This function has no parameters. It returns a value that identifies the cause of errors.

  • JSON_ERROR_NONE - No errors
  • JSON_ERROR_SYNTAX - Syntax error
  • JSON_ERROR_UTF8 - Incorrect UTF-8 characters, possibly incorrect encoding
  • JSON_ERROR_DEPTH - Maximum stack depth reached
  • JSON_ERROR_STATE_MISMATCH - Invalid or incorrect JSON
  • JSON_ERROR_CTRL_CHAR - Control character error, possibly incorrect encoding

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. Using 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 handles this event and sends an ajax request to PHP script y, passing the picture ID.
  • On the server, php receives the description of the picture, the name of the picture, the address to 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.
  • Lastly, since JSON is identical to objects in JavaScript, you can easily take this example and create from it JavaScript object:

    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.

    We create JavaScript variable from 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 the availability of data and display some information using modal window alert.

    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 data about the contents of the cart 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.

    Generating a JSON string from 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 in the future you want to use data in the form associative array, just pass the second parameters 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 has been part of the ECMAScript standard since 1999, when ECMA defined the eval() function to handle the format. It began to gain popularity along with the growing success of Ajax. The word JSON often comes up when someone talks about Ajax. It is known that JSON is a different data format, that it replaces XML, and that many programmers actively support it. But what exactly is JSON and what are its benefits?

    Why JSON?

    The advantage of JSON is that it is parsed by JavaScript. There is no need to parse the document, as is the case with XML, to transmit data over the Internet.

    JSON and XML

    Advantages of JSON:

    • Easy to read and understand.
    • Easy to use.

    Advantages of XML:

    • Has expansion options

    Both XML and JSON have the ability to integrate large amounts of data in binary form.

    JSON syntax

    JSON components:

    • Objects: Contain objects or attributes.
    • Scalar variables: number, string, logical variable.
    • Array.
    • Literal values: null, true, false, "character string", and numeric values.
    An object

    Contains an element or a list of elements, where each element is described as follows:

    "name" : "value"

    Object syntax:

    ( element, element, .... )

    Array

    A set of values ​​separated by comma.

    [meaning, meaning, ....]

    Meaning

    The value can be: object, array, literal value (string, number, true, false, null).

    You don't need anything else to create a JSON file!

    Example JSON file

    A simple example of a menu structure. IN this object contains attributes and an array that includes other menu bar objects.

    ( "menu": "File", "commands": [ ( "title": "New", "action": "CreateDoc" ), ( "title": "Open", "action": "OpenDoc" ), ( "title": "Close", "action": "CloseDoc") ] ) XML equivalent: File New CreateDoc Open OpenDoc Close CloseDoc

    How to use the format

    A JSON file allows you to download data from or to a server. For example, saving the contents of a form that was just filled out by the user. The process includes three phases: browser processing, server processing, and data exchange between them.

    Client part (browser)

    This part is fairly easy since JSON is part of the JavaScript definition. The contents of the file or defining data are assigned to variables and they become program objects.

    Server part

    The JSON file is used by various programming languages, including PHP and Java, thanks to the presence of parsers that allow you to retrieve the content and even convert it into classes and attributes of the language. On the JSON website you can find parsers for many programming languages.

    Data exchange
    • using XMLHttpRequest.

    The JSON file is processed by a JavaScript function eval(). Posting a file to the server can be done using XMLHttpRequest. The file is sent as a text file and is processed by the programming language parser used on the server.

    Example

    XMLHttpRequest code:

    Var req = new XMLHttpRequest(); req.open("GET", "file.json", true); req.onreadystatechange = myCode; // handler req.send(null);

    JavaScript handler:

    Function myCode() ( if (req.readyState == 4) ( var doc = eval("(" + req.responseText + ")"); ) ) Data usage: var menuName = document.getElementById("jsmenu"); // look for the field menuName.value = doc.menu.value; // assign a value to a field How to get data: doc.commands.title // read the value of the "title" field in the array doc.commands.action // read the value of the "action" field in the array

    If you have installed on your computer antivirus program You can scan all files on your computer, as well as each file individually. You can scan any file by clicking right click mouse on the file and selecting the appropriate option to scan the file for viruses.

    For example, in this figure the file my-file.json is highlighted, then you need to right-click on this file and select the option “scan with AVG” in the file menu. When you select this option, it will open AVG Antivirus, which will perform the check this file for the presence of viruses.


    Sometimes the error may occur as a result of incorrect installation software, which may be due to a problem encountered during the installation process. This may prevent your operating system from associating your JSON file with the correct application software, influencing so-called "file extension associations".

    Sometimes a simple reinstallation Mozilla Firefox may solve your problem by binding JSON correctly with Mozilla Firefox. In other cases, problems with file associations may result from poor programming of the software by the developer, and you may need to contact the developer for further assistance.


    Tip: Try updating Mozilla Firefox to latest version to make sure you have the latest patches and updates installed.


    This may seem too obvious, but often the JSON file itself can be the cause of the problem. If you received the file via an attachment Email or downloaded it from a website and the download process was interrupted (such as a power outage or other reason), the file may become corrupted. If possible, try getting a new copy of the JSON file and try opening it again.


    Caution: A damaged file may cause collateral damage to a previous or existing malware on your PC, so it is very important to keep an updated antivirus running on your computer at all times.


    If your JSON file is associated with hardware on your computer, you may need to update the device drivers associated with that hardware in order to open the file.

    This problem is usually associated with media file types that depend on the successful opening of hardware inside the computer, e.g. sound card or video cards. For example, if you are trying to open an audio file but cannot open it, you may need to update your sound card drivers.


    Tip: If you receive an error message related to .SYS file when you try to open a JSON file, the problem may likely be due to corrupt or outdated device drivers that need to be updated. This process can be made easier by using driver update software such as DriverDoc.


    If the steps did not resolve the issue and you are still having trouble opening JSON files, it may be due to a lack of available system resources. Some versions of JSON files may require a significant amount of resources (e.g. memory/RAM, processing power) to properly open on your computer. This problem occurs quite often if you are using a fairly old computer. Hardware and at the same time a much newer operating system.

    This problem can occur when the computer has difficulty completing a task because operating system(and other services running in background) may consume too many resources to open a JSON file. Try closing all applications on your PC before opening Mozilla Firefox Bookmarks Backup. Freeing up all available resources on your computer will provide the best conditions for attempting to open the JSON file.


    If you've followed all the steps above and your JSON file still won't open, you may need to perform a hardware update. In most cases, even when using older versions of hardware, the processing power may still be more than sufficient for most custom applications(unless you're doing a lot of CPU intensive work like 3D rendering, financial/scientific modeling or multimedia intensive work). Therefore, it is likely that your computer does not have enough memory (more commonly called "RAM" or RAM) to perform the file open task.