JSON Basics
Simply put, JSON converts a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or from a web client in an asynchronous application Passed to the server-side program. This string looks a little weird (you'll see a few examples later), but JavaScript interprets it easily, and JSON can represent more complex structures than name/value pairs. For example, arrays and complex objects can be represented rather than just simple lists of keys and values.
Simple JSON example
In its simplest form, a name/value pair can be represented by JSON like this:
{ "firstName": "Brett" }
This example is very basic and actually takes up more space than the equivalent plain text name/value pair:
firstName=Brett
However, JSON comes into its own when you string multiple name/value pairs together. First, you can create a record containing multiple name/value pairs, such as:
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }
Syntax-wise this isn't a huge advantage over name/value pairs, but in this case JSON is easier to use and more readable. For example, it makes it clear that the above three values are part of the same record; the curly braces make the values somehow related.
Array of values
When you need to represent a set of values, JSON can not only improve readability, but also reduce complexity. For example, suppose you want to represent a list of people's names. In XML, many start and end tags are required; if you use typical name/value pairs (like the ones you saw in previous articles in this series), a proprietary data format must be created , or change the key name to the form person1-firstName.
If using JSON, just group multiple records with curly braces together:
There are no predefined constraints that need to be adhered to when processing JSON formatted data. Therefore, within the same data structure, the way the data is represented can be changed, and the same thing can even be represented in different ways.
Using JSON in JavaScript
Once you master the JSON format, using it in JavaScript is simple. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.
Assign JSON data to variables
For example, you can create a new JavaScript variable and assign the JSON-formatted data string directly to it:
Access Data
Although it may not seem obvious, the long string above is actually just an array; you can easily access this array by placing it in a JavaScript variable. In fact, just use dot notation to represent array elements. So, to access the last name of the first entry in the programmers list, just use code like this in JavaScript:
people.programmers[0].lastName;
Note that array indexing is zero-based. So, this line of code first accesses the data in the people variable; then moves to the entry called programmers, then moves to the first record ([0]); and finally, accesses the value of the lastName key. The result is the string value "McLaughlin".
Here are a few examples using the same variable.
Modify JSON data
Just as data can be accessed using periods and brackets, data can be easily modified in the same way:
people.musicians[1].lastName = "Rachmaninov";
After converting the string into a JavaScript object, you can modify the data in the variable like this.
Convert back to string
Of course, all data modifications are of little value if you can't easily convert the object back to the text format mentioned in this article. This conversion is also simple in JavaScript:
String newJSONtext = people.toJSONString();
That’s it! You now have a text string that you can use anywhere, for example, as a request string in an Ajax application.
More importantly, any JavaScript object can be converted to JSON text. It is not only possible to handle variables originally assigned with JSON strings. To convert an object named myObject, just execute a command of the same form:
String myObjectInJSON = myObject.toJSONString();
This is the biggest difference between JSON and the other data formats discussed in this series. If you use JSON, you only need to call a simple function to get the formatted data, ready to use. For other data formats, conversion between raw and formatted data is required. Even when using an API like the Document Object Model (which provides functions to convert your own data structures to text), you need to learn the API and use the API's objects instead of using native JavaScript objects and syntax.
The final conclusion is that if you are dealing with a large number of JavaScript objects, then JSON is almost certainly a good choice so that you can easily convert the data into a format that can be sent to the server-side program in the request.
Application of JSON in PHP
In today’s Internet, AJAX is no longer an unfamiliar word. Speaking of AJAX, XML that emerged due to RSS may immediately come to mind. XML parsing is probably no longer a problem, especially with PHP5 and the emergence of a large number of XML parsers, such as the most lightweight SimpleXML. However, for AJAX, XML parsing is more inclined to the support of front-end Javascript. I think everyone who has parsed XML will be confused by trees and nodes. It is undeniable that XML is a very good data storage method, but its flexibility makes it difficult to parse. Of course, the difficulty referred to here is relative to the protagonist of this article - JSON.
What is JSON? I won't repeat the concept. In layman's terms, it is a data storage format, just like a PHP serialized string. It is a data description. For example, if we serialize an array and store it, it can be easily deserialized and applied. The same is true for JSON, except that it builds an interactive bridge between client-side Javascript and server-side PHP. We use PHP to generate the JSON string, and then pass this string to the front-end Javascript. Javascirpt can easily convert it into JSON and then apply it. To put it in layman's terms, it really looks like an array.
Back to business, how to use JSON. PHP5.2 has built-in support for JSON. Of course, if it is lower than this version, there are many PHP version implementations on the market, just use whichever one you want. Now we mainly talk about the JSON built-in support of PHP. Very simple, two functions: json_encode and json_decode (very similar to serialization). One for encoding and one for decoding. Let’s first look at the use of encoding:
Server-side JSON
Send JSON to server
Sending JSON to the server is not difficult, but it is crucial and there are some important choices to make. But once you decide to use JSON, the choices you make are simple and limited, so there's not much to think about and focus on. The important thing is to be able to send a JSON string to the server, preferably as quickly and as easily as possible.
Send JSON as name/value pairs via GET
The easiest way to send JSON data to a server is to convert it to text and send it as a name/value pair. It's important to note that the JSON-formatted data is a fairly long object and might look like Listing 1:
Listing 1. Simple JavaScript object in JSON format
There are two disadvantages of this approach:
There is a length limit on URL strings when sending large chunks of data using GET requests. While this limit is broad, the JSON string representation of an object can be longer than you think, especially when working with extremely complex objects.
When sending all data across the network in plain text, the insecurities of sending data are more than you can handle.
In short, the above are two limitations of GET requests, not simply two things related to JSON data. These two may require a little more attention when you want to send more content than just the username and last name, such as selections in a form. To handle any confidential or extremely long content, you can use POST requests.
Use POST request to send JSON data
When you decide to use a POST request to send JSON data to the server, you don't need to make a lot of changes to your code, like this:
Another simple tip is that the URL has time appended to the end. This ensures that the request is not cached the first time it is sent, but is recreated and resent each time this method is called; the URL will be slightly different due to different timestamps. This technique is often used to ensure that a POST to a script actually generates a new request each time and that the web server does not attempt to cache the response from the server.
JSON is just text
Whether you use GET or POST, the key point is that JSON is just text. Since no special coding is required and every server-side script can handle text data, JSON can be easily leveraged and applied to the server. It's not that simple if the JSON is in binary format or some weird text encoding; luckily JSON is just regular text data (as the script can receive from form submissions, in the POST section and Content-Type header can also be seen in ), so you don't need to worry too much when sending the data to the server.
Interpret JSON on the server
Once you have written client-side JavaScript code that allows users to interact with Web forms and Web pages, and collects the information needed to be sent to the server-side program for processing, the server becomes the application (if you call Server-side programs used asynchronously may be the protagonists in what we think of as so-called "Ajax applications"). At this point, the choices you make on the client side (such as using a JavaScript object and converting it to a JSON string) must match the choices you make on the server side, such as which API to use to decode the JSON data.
Two steps for processing JSON
No matter what language is used on the server side, processing JSON on the server side basically requires two steps.
Find the corresponding JSON parser/toolbox/helper API for the language you are writing your server-side program in.
Use the JSON parser/toolbox/helper API to take request data from the client and turn the data into something your script can understand.
The above is almost the general content that you should know now. Next, we introduce each step in more detail.
Find a JSON parser
The best resource for finding a JSON parser or toolkit is the JSON site (see Resources for a link). Here, in addition to learning all about the format itself, you'll find links to various tools and parsers for JSON, from ASP to Erlang to Pike to Ruby. Just download the appropriate toolbox for the language you're writing scripts in. To enable server-side scripts and programs to use this toolbox, it can be selected, extended, or installed as appropriate (more variability if you are using C#, PHP, or Lisp on the server side).
For example, if you are using PHP, you can simply upgrade to PHP 5.2 and use it; this latest version of PHP includes the JSON extension by default. In fact, that's the best way to handle JSON when using PHP. If you are using Java servlets, the org.json package at json.org is an obvious choice. In this case, you can download json.zip from the JSON Web site and add the source files it contains to the project build directory. After compiling these files, everything is ready. You can use the same steps for the other supported languages; the language you use depends on your proficiency in the language, and it is best to use a language you are familiar with.
Use JSON parser
Once you have obtained the resources available to the program, the only thing left is to find the appropriate method to call. For example, suppose you are using the JSON-PHP template for PHP:
With this template, all data obtained (anything in array format, multi-line, single value or JSON data structure) can be converted into native PHP format and placed in the $value variable.
If the org.json package is used in the servlet, the following code will be used: