What is json. JSON format: what it is, how to create and open a file

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

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

Data exchange: browser - server

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

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

Since the content of the pages of modern sites has really become "massive" (voluminous), the effectiveness of the format for data exchange has acquired particular importance. This is not to say that JSON has become a new representation of data, but the fact that it has long been a part of JavaScript syntax is significant.

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

Cyrillic and JSON

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

It is doubtful that the initiative in Cyrillic names will be supported by the external environment of the browser, with which it constantly has to deal. But this fact deserves attention for the simple reason that the JSON format is the ability to write names and values \u200b\u200bas the developer wants. This is essential, since in each task, describing the scope as it requires it greatly simplifies debugging and reduces the number of errors.

It doesn't matter what kind of basis the syntactic innovation was based on - JSON, it is important that it gave a legal right and a real opportunity to put the correspondence: "any name \u003d any value".

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

PHP and JSON

By accepting data in JSON format, the server (through PHP, in particular) provides the ability to process it as it is and return the result back to the browser in a similar format. PHP original array:

  • $ cJSON \u003d array ("a" \u003d\u003e "alfa", "b" \u003d\u003e "beta", "g" \u003d\u003e "gamma").

Convert to JSON format for transmission to browser:

  • $ cJS \u003d json_encode ($ cJSON).

Result:

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

The nesting shown in the photo is allowed.

Here the generated array was added by a new element "in itself" with the automatic index "0", and then again with the specified index "z".

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

Nesting level

Elements can be nested within each other both on the browser side and on the server side. In practice, the JSON format (as described in RFC 4627) provides significantly more than 4 levels of nesting, but this feature should not be abused.

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

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

JSON files

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

Enterprise staff and JSON format: example

Usually, a record about one person is a surname, name, patronymic, year of birth, specialty, education, ... and a few more simple meanings. Even in particularly demanding companies, a record about one person will not exceed ten or two fields. It is perceivable and can be placed in a database string.

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

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

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

This is an example of the content of a file generated by a site that provides a color volumetric printing service for mugs and ceramics. Naturally, deciding, having such a JSON format, than opening it, is really problematic. However, in this and similar cases, there are no problems with reading the file: PHP reads the file, parses it and transfers it to the browser. The data changed by the visitor are returned to the server and written back.

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

JSON is often used to store and use service information - this is not a staffing table, it is not necessary for either the developer or the site visitor to see it.

XML and JSON

"Everything in good time" is a classical knowledge taken as an axiom even before the advent of programming. "Nothing appears just like that" - this was also before a person wrote the first intelligible program in artificial language.

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

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

There were cases in practice when programs were written in BASIC that did not use JSON as such, but perfectly store "name \u003d value" pairs and put them at the disposal of the right algorithms at the right time.

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

The habit of working with associative arrays and objects in JavaScript makes using JSON natural and convenient. It's a really great format, but the skill of separating and concatenating by manipulating strings and arrays has much deeper roots.

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

Using JSON in Android

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

In this case, it is the JSON format that is used. Perhaps this is so, but the question is not about the phenomenality of social networks, but about the fact that the presentation of information in the "name \u003d value" format is really convenient for both programming and use. Unlike strict and complex "XML", this is a truly human-friendly format.

Associative arrays

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

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

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

Associative array -\u003e JSON

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

The second array contains data for the page:

  • orientation (landscape or normal);
  • vertical and horizontal dimensions;
  • indents (margins to the left, top, bottom, right);
  • headers and footers.

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

Dynamic variables

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

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

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

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

You've probably heard of JSON sometime. What is it? What can he do and how can he use it?

In this tutorial, we'll cover the basics of JSON and cover the following points:

  • What is JSON?
  • What is JSON used for?
  • How do I 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 simple syntax, you can easily store anything from one 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 is created, it is easy to send it to another application or elsewhere on the web because it is plain text.

JSON has the following benefits:

  • It is compact.
  • His sentences are easy to read and compose by both human and computer.
  • It is easy to convert it to a data structure for most programming languages \u200b\u200b(numbers, strings, booleans, arrays, etc.)
  • Many programming languages \u200b\u200bhave functions and libraries for reading and creating JSON structures.

JSON stands for JavaScript Object Notation. As the name suggests, it is based on the way objects are defined (much like creating associative arrays in other languages) and arrays.

What is JSON used for?

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

  1. The user clicks a product thumbnail in the online store.
  2. JavaScript running on the browser generates an AJAX request to the PHP script running on the server, passing in the selected product ID.
  3. 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.
  4. JavaScript running in the browser receives a 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. This method is less common, however, as passing data through AJAX requests can be simplified. For example, the product ID can 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 get data using JSON through AJAX requests.

How do I create a JSON string?

There are some basic rules for creating a JSON string:

  • The JSON string contains either an array of values \u200b\u200bor an object (an associative array of name / value pairs).
  • Array 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.
  • Value 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 must use a backslash: \\ ". As with many programming languages, you can put control characters and hexadecimal codes in a string, preceded by a backslash. See the JSON site for details.

A 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 ":" Wonder product "," quantity ": 3)], "orderCompleted": true)

Consider the line in detail:

  • We create an object using curly braces ((and)).
  • The object has several name / value pairs: "orderID": 12345 Property named "orderId" and integer value 12345 "shopperName": "Vanya Ivanov" property named "shopperName" and string value "Vanya Ivanov" "shopperEmail": " [email protected]"Property named" shopperEmail "and string value" [email protected]"" contents ": [...] A property named" contents "whose value is an array" orderCompleted ": true A property named" orderCompleted "with a Boolean value true
  • There are 2 objects in the "contents" array that represent the 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:

Comparing JSON and XML

In many ways, you can think of JSON as an alternative to XML, at least for web applications. 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 more and more popular for carrying AJAX data.

While XML is a proven technology that is used in a fair number of applications, the advantages of JSON are that it is a more compact and easier to understand data format.

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

orderID 12345 shopperName Ваня Иванов shopperEmail [email protected] contents productID 34 productName Супер товар quantity 1 productID 56 productName Чудо товар 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 difficult to read.

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 manually creating a JSON string is tedious. In addition, you often need to take a JSON string, convert its content into a variable that can be used in the code.

Most programming languages \u200b\u200bhave 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 content. For example, let's create a JavaScript object that contains the order information from our example, and then create a JSON string from it:

This code will give:

Note that the JSON.stringify () method returns a JSON string without spaces. It is more difficult to read, but 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 receives a JSON string and returns a JavaScript object or array that contains the data. For instance:

We've created a jsonString variable that contains the JSON string of our example ordering. 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 printing out the properties of the shopperEmail object and productName in the contents array.

As a result, we get the following output:

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

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

Working with a JSON string in PHP

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

Create JSON string from PHP variable

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

12345, "shopperName" \u003d\u003e "Vanya Ivanov", "shopperEmail" \u003d\u003e " [email protected]"," contents "\u003d\u003e array (array (" productID "\u003d\u003e 34," productName "\u003d\u003e" Super product "," quantity "\u003d\u003e 1), array (" productID "\u003d\u003e 56," productName "\u003d\u003e "Wonder product", "quantity" \u003d\u003e 3)), "orderCompleted" \u003d\u003e true); echo json_encode ($ cart);?\u003e

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 the AJAX response to the browser, where the JavaScript code uses the JSON.parse () method to convert it back to 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 content of variables into a JSON string.

Create a variable from a JSON string

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

shopperEmail. "
"; echo $ cart-\u003e contents-\u003e productName."
"; ?>

As for 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. Therefore, we use -\u003e to access the properties of the object in the example above.

If you want a JSON object as an associated PHP array, you need to pass true as the second argument to the json_decode () function. For instance:

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

This code will give the same output:

[email protected] Miracle product

You can also pass other arguments to json_decode () to specify the depth of recursion 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 the most important tool in your workshop.

Json (JavaScript Object Notation) is a structured data presentation format used to transfer data over the Internet.

In fact, the JSON format is a regular string.

JSON syntax

The JSON syntax is rather small, it only includes a description of what the transmitted data looks like.

JSON data types

In JSON, data types can be divided into two categories: simple and complex.

  • string - text strings (usually called simply - strings)
  • number - numbers
  • boolean - logical (boolean) values
  • null

Complex types include:

  • object - objects
  • array - arrays

JSON syntax is borrowed from JavaScript, so the syntax is the same as in JavaScript to represent values \u200b\u200bof simple and complex types.

Simple values

The simplest example of JSON code is any value of a simple type:

5 2.3 "Hello!" true null

In JSON, strings must be enclosed in double quotes only. Using single quotes results in a syntax error.

Objects

A JSON object is a list of zero or more properties (name: value pairs) enclosed in curly braces, separated by commas. Object property names must be enclosed in double quotes. Missing double quotes or using single quotes in the property name is an error. Properties can contain values \u200b\u200bof any type (simple or complex):

("name": "Gomer", "age": 40, "work": ("place": "Nuclear plant", "location": "Springfield"))

Arrays

A JSON array is a comma-separated list of zero or more values, enclosed in square brackets. An array can contain values \u200b\u200bof any type (simple or complex):

[("name": "Gomer", "age": 40, "work": ("place": "Nuclear plant", "location": "Springfield"), "children": ["Bart", "Lisa "," Maggie "]), (" name ":" Marge "," age ": 37," work ": (" place ":" Home "," location ":" Springfield ")," children ": [ "Bart", "Lisa", "Maggie"])]

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 about 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 the json format. We will follow the following topics:

  • What is JSON format?
  • How do I 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 transmit structured data. With a simple syntax, you can easily save both simple numbers and strings, as well as arrays, objects, using nothing more than text. You can also bind objects and arrays, which allows you to create complex data structures.

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

JSON has many benefits:

  • It's compact
  • It is human-readable and computer readable
  • It can be easily converted to programmatic formats: numeric values, strings, boolean format, zero value, arrays and associative arrays.
  • Almost all programming languages \u200b\u200bhave functions to read and create json data format.

Literally, the abbreviation 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 JSON used for?

Most of all, json is used to exchange data between javascript and the 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 with an example:

  1. User clicks on thumbnail pictures
  2. JavaScript handles this event and sends an ajax request to the PHP script, passing the image ID.
  3. On the server, php gets the description of the image, the name of the image, the address to the large image and other information from the database. After receiving it, it converts it to JSON format and sends it back to the user's page.
  4. JavaScript receives a JSON response, processes the data, generates html code and displays an enlarged image with description and other information.

This is how the picture 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 functions getJSON () and parseJSON (), which help to work with the format through ajax requests.

How do I create JSON strings?


Below are the basic rules for creating JSON strings:

  • The JSON string contains both an array of values \u200b\u200band an object (an associative array with name / value pairs).
  • The array must be wrapped in square brackets, [and], may contain a list of values, separated by comas.
  • Objects wrap with curly arms, (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 \u200b\u200bin an array or object can be:
    • Numeric (whole or decimal point)
    • String (wrapped in double quotes)
    • Boolean (true or false)
    • Other arrays (wrapped in square brackets [and])
    • Other objects (wrapped in curly bow (s))
    • 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 "shopping cart" of an online store using 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 down this data piece by piece:

  1. At the beginning and end, we use curly bow (s) that make it clear that this is an object.
  2. Inside the object, we have several name / value pairs:
  3. "orderID": 12345 - field named orderId and value 12345
  4. "shopperName": "John Smith" - field named shopperName and value John Smith
  5. " shopperEmail ":"[email protected] example.com " - similarly to the previous field, the customer's email is stored here.
  6. "contents": [...] - a field named content whose value is an array.
  7. "orderCompleted": true - a field named orderCompleted, whose value is true
  8. 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 JavaScript objects, you can easily take this example and create a JavaScript object from it:

Comparing JSON to XML

In most cases, you will think of JSON as an alternative to XML - at least for web applications. Concept of Ajax, originally uses XML to exchange data between server and browser, but in recent years JSON has become more popular for transferring ajax data.

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

Here's 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 via PHP and JS?

So 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


Despite the fact that JSON format is simple, it is difficult to write it by hand when developing web applications. Moreover, you often need to convert JSON strings into variables and then use them in your code.

Fortunately, many programming languages \u200b\u200bprovide tools for working with JSON strings. The main idea of \u200b\u200bwhich:

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

ReadingJSON strings, you start with a JSON string containing specific data, pass 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.

This is what will be displayed:

("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 a JavaScript variable from a JSON string

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

Here we have created a variable, jsonString, that contains the JSON string from the examples provided earlier. Then we passed this string through JSON.parse () to create an object containing JSON data that is 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 accept 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 with PHP


PHP, like JavaScript, has functions to convert variables to JSON format, and vice versa. Let's take a look at them.

Generating JSON string from PHP variable

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

12345, "shopperName" \u003d\u003e "John Smith", "shopperEmail" \u003d\u003e " [email protected]"," contents "\u003d\u003e array (array (" productID "\u003d\u003e 34," productName "\u003d\u003e" SuperWidget "," quantity "\u003d\u003e 1), array (" productID "\u003d\u003e 56," productName "\u003d\u003e" WonderWidget "," quantity "\u003d\u003e 3))," orderCompleted "\u003d\u003e true); echo json_encode ($ cart);?\u003e

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 PHP variable from JSON string

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

shopperEmail. "
"; echo $ cart-\u003e contents-\u003e productName."
"; ?>

As with JavaScript, this code will output the following:

[email protected] WonderWidget

By default, json_decode () returns JSON objects as PHP objects. Similar to the familiar syntax, we use -\u003e to access object properties.

If in the future you want to use the data in the form of an associative array, just pass the second parameters true to the json_decode () function. Here's an example:

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

This outputs the same result:

[email protected]com WonderWidget

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, undoubtedly use the JSON format to exchange data between the server and the browser.


Announcement

The JSON Website File Format

JSON files are used to store structures of simple arrays of data using a human-readable text-based format. Initially, JSON files were closely related to the JavaScript programming language, but due to the fact that this format currently supports a large number of programming APIs, it can be considered as a format that is not tied to any programming language. This alternative to XML is most commonly used by Ajax web applications.

Technical details for JSON files

JSON files are used as files for data exchange. This exchange often occurs between computers connected over the Internet. Thus, it is very rare for JSON files to be saved on a computer's hard drive. Some applications, however, still use this format. For example, Google+ profile data is saved and loaded in JSON format, and the Mozilla Firefox web browser uses this format to store backup copies of bookmarks.

More information on the JSON format



File extension .json
File category
Example file (0.57 KiB)
Related programs Microsoft Notepad
Microsoft WordPad
Notepad ++
Mozilla Firefox