Quantcast
Viewing all articles
Browse latest Browse all 10

JSON, The New XML

When you write for the web, you may want to send data to another server or to a client. A common way to transfer that data is in XML format. The data will then be processed using SAX, DOM or XPath. Every language support it.

If what you want is to define a variable, an object or an array in Javascript, you can use the JSON extension. JSON is an acronym for ‘Java Script Object Notation’. In Javascript you can use it as follows:

var myObject=<?php echo json_encode($php_object); >;

Here no parsers are required.

Here’s an example of using it in PHP:

<?
class my_class {
  public $prop1;
  public $prop2;

  function __construct(){
    $this->prop1='a';
    $this->prop2=400;
  }
}

$obj=new my_class();
echo json_encode($obj);
?>

The output looks like:
{“prop1″:”a”,”prop2″:400}

In addition to encoding, a JSON string can be decoded into an object in a language other than Javascript. Thus, you can pass data in the JSON format to any program supporting JSON, and, as you can see in www.json.org, most languages used today support it.

The ability to encode varibles into JSON and decode it back in any language is not the only reason why JSON can replace XML. If you go to www.json.org, you can see links in the bottom referring to other sites. For example, JSONPath, that allows you to access a member just like XPath. JSONPath is available in PHP and Javascript.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles