JSON vs XML
I’m learning about web services and in the process came across JSON as a viable substitute for XML. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read/write by humans and also easy to parse in most applications.
JSON is based on 2 structures: The Object & The Array.
Compared to XML, JSON can represent the exact same data with fewer characters since it doesn’t have tags, so in the grand scheme will be lighter.
One of the reasons it is used when returning information to a browser based application is because it can be used in JavaScript and Ajax without any need to be parsed unlike XML that has to be parsed. In addition it’s lighter, and in PHP ver 5.2 and up, a json_encode() function automatically converts a PHP array into a JSON object.
The following is an example of JSON data representation:
{
“firstName”: “John”,
“lastName”: “Smith”,
“age”: 25,
“address”:
{
“streetAddress”: “21 2nd Street”,
“city”: “New York”,
“state”: “NY”,
“postalCode”: “10021″
},
“phoneNumber”:
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
As shown above, The object has string fields for first name and last name, a number field for age, contains an object representing the person’s address, and contains a list (an array) of phone number objects.