Art AboutFAQWrite for usContact InfoRSS Feed
Search A/R/T:

JSON and PHP: More Than Web Services

by Marco Tabini — Page 1 of 4
Click to rate:    
444 votes / avg. rating 6.46%

In the midst of all the wonderful AJAX libraries in the wild, many today still don't understand the underlying technologies of AJAX that make it so powerful. In this article php|architect's publisher Marco Tabini covers JSON, the magic format that makes serializing data between Javascript and other languages (often server-side) a breeze. Simplicity, velocity and power are the gifts of JSON.


 

Ah, complexity: the mother of all consulting fees!

For developers who cut their teeth on the computers of yesteryear, some aspects of today's programming world are quite puzzling. If you remember a time when 48kB of RAM could only be acquired in exchange for several months' worth of savings, the fact that your average empty Microsoft Word document wouldn't fit in the entire amount of memory once available to your entire computer (including operating system and programming language) is very disturbing. Ditto if your first hard disk weighed ten pounds and required about thirty seconds to whirr up to speed.

To people like these, the evolution of the lowly text file into today's uber-complex monsters just sounds wrong. We have somehow managed to delude ourselves that the Internet's pervasion of every sort of market and application requires that every single communication take place using technologies designed to handle everything from ice cream flavours to the plans for a nuclear power plant. Witness the explosion of the XML phenomenon, and its monstrous children, like XML-RPC and SOAP are complex enough to require automated tools for generating the code required to generate the requests and responses required to run a web service. Try saying that three times in a row!

A Simpler, Gentler Protocol

The truth is that XML and XML-based web service protocols, while useful in the right scenarios, are overkill for most applications. You probably don't need an iron-clad error reporting mechanism and super-strict data typing if all you're trying to do is pull a list of pictures from your favourite photo storage service so that you can show them on your web page. On the other hand, having to parse XML with Javascript—a language whose browser support is about as consistent as HTML's—is loads of fun and fully justifies the hell you have to go through to get SOAP working server-side... not.

In the past year or so, a lot of support has been building up for JSON, which stands for JavaScript Object Notation. JSON is a format indigenous to Javascript that makes it possible to encapsulate arbitrary data in an object wrapper and serialize it to plain—just like php's serialize() function, or XML.

There are two main differences between JSON and the other serialization techniques that make it uniquely suited to web service data interaction:

  • Javascript understands JSON natively, which means that you won't have to do any parsing on the client side
  • JSON is very compact and extremely simple, which makes it ideal for complex AJAX interfaces and busy websites where bandwidth and server-side processing power comes at a premium. Its simplicity also makes implementing a JSON parser very simpler in practically every language
On the flip side, JSON does not offer the level of consistency and accuracy that XML can provide, nor does it offer many of the advanced characteristics of SOAP, such as a well-defined error-reporting mechanism or proper data typing.

Think of JSON as a scooter, and SOAP as an armoured vehicle. Your bank probably won't trust its money to the former, but you don't need the latter if you're pulling search results from Yahoo!

 


 Tags:  ,
 Add tag(s) (comma separated):
[Tags beta] — [Add New][Help]  

Tags Help

Tags are keywords associated with a web page that help classifying information. You can find a good explanation here.

To add one or more tags to this page, simply enter them below (separate them with a comma) and hit enter or click on the "Go" button.

New Comment
This form allows you to type in a new comment. Keep in mind the following:
  • The system accepts input in plain text format. Newlines will be converted to the HTML equivalent, and the system will try to catch most URLs and make them clickable.
  • Your e-mail address will never be displayed. We will use it only to notify you when new comments are posted to this page.
  • As a rule, we do not delete comments unless they are offensive, racist, spam or otherwise inappropriate.
  • Bold fields are required
Your Name:
Your e-mail:
Type this number:
Subject:
Comment:
Comments   New Comment
Re: JSON and PHP: More Than Web Services (#72)
By Gaetano Giunta on 2006-05-25 03:59:38

A couple of notes:

- take care when directly using eval() on the browser: if the library used to generate the json data is not 100% safe, it might open up the door to javascript injection (ie. if data to eb json encoded is fed to website by malicious user)

- another php lib offering support for json encoding-decoding is phpxmlrpc, in the 'extras' package

[Reply to this]

Re: Re: JSON and PHP: More Than Web Services (#74)
By smiley on 2006-05-25 12:13:26

Excellent article, thank you very much

just a question, will the above example html/javascript page work in all latest browsers?

[Reply to this]

Re: Re: Re: JSON and PHP: More Than Web Services (#75)
By Marco on 2006-05-25 13:26:10

It should work with all reasonably recent browsers, since it makes heavy use of the Yahoo! UI Library. Their compatibility statement is here:

[Reply to this]

Re: Re: Re: Re: JSON and PHP: More Than Web Services (#79)
By Marco on 2006-05-26 06:45:59
Re: Re: JSON and PHP: More Than Web Services (#76)
By Marco on 2006-05-25 13:27:09

Fair point%u2014but, in this case, the source of the data *is* trusted :)

[Reply to this]

Re: JSON and PHP: More Than Web Services (#73)
By Jim Plush on 2006-05-25 12:07:42

I've moved to use JSON at Panasonic not just for ajax applications but also as the transport for our system events sent by network devices. This is a reason I coded the MyBic ajax framework to use JSON by default and instead of eval()'ing the string I use json.org's serializer code.

JSON is supported in pretty much every major language and is a great little alternative to XML in most cases. One thing I'm going to be working on is a validator for JSON strings so you can validate against a document like an XSD file does.

[Reply to this]

JSON with PHP5 as CGI? (#239)
By LordMerlin on 2006-07-23 11:12:54

I have setup both PHP4 & PHP5 on my cPanel server. Well, PHP4 was already installed, as an Apache Module. So I have added php5, according to this link:

[Reply to this]

Re: JSON and PHP: More Than Web Services (#509)
By Regina Mullen on 2007-03-30 21:37:20

Thanks for the article, Marco!

The Windows install worked a charm, no problem!

However, your first example needed a slight modification. It comes out right if you substitute

$decodedObject = json_decode ($jsonPayload);
$decodedArray = json_decode ($jsonPayload, true);

and use the previous example array instead of using an empty $_POST value.


[Reply to this]

Re: Re: JSON and PHP: More Than Web Services (#620)
By Regina on 2007-12-26 16:45:42

Follow up...only 9 months later. For those lazy folks using php5, the Fibonacci sequence needs a tweak:

var jsonData = eval ('(<?= $jsonData ?>)');

becomes

var jsonData = eval ('(<?php print $jsonData; ?>)');

I know it should work the other way, but this was quick and dirty.

[Reply to this]

So now what? (#659)
By Andrew on 2008-08-22 12:54:59

Your last line says we shouldn't rely on Javascript to display our JSON. So how do we iterate through the JSON string and display it on the front end? Without forcing the user to have Javascript running.

I feel like you left off the part of the tutorial that I came looking for.

[Reply to this]

Index