Until now, we have seen how parsers in JavaScript support JSON. There are many other programming languages that provide implementations for JSON. Languages such as PHP, Python, C#, C++, and Java provide very good support for the JSON data interchange format. All of the popular programming languages that support service-oriented architectures understand the importance of JSON and its implementation for data transfer, and thus have provided great support for JSON. Let us take a quick detour from implementing JSON in JavaScript, and see how JSON is implemented in other languages, such as PHP and Python.
Languages that support JSON
JSON implementation in PHP
PHP is considered to be one of the most popular languages for building web applications. It is a server-side scripting language and allows developers to build applications that can perform operations on the server, connect to a database to perform CRUD (Create, Read, Update, Delete) operations, and provide a stately environment for real-time applications. JSON support has been built into the PHP core from PHP 5.2.0; this helps users avoid going through any complex installations or configurations. Given that JSON is just a data interchange format, PHP consists of two functions. These functions handle JSON that comes in via a request or generate JSON that will be sent via a response. PHP is a weakly-typed language; for this example, we will use the data stored in a PHP array and convert that data into JSON string, which can be utilized as a data feed. Let us recreate the student example that we used in an earlier section, build it in PHP, and convert it into JSON:
<?php
$student = array(
"id"=>101,
"name"=>"John Doe",
"isStudent"=>true,
"scores"=>array(40, 50);
"courses"=>array(
"major"=>"Finance",
"minor"=>"Marketing"
);
);
//Echo is used to print the data
echo json_encode($student); //encoding the array into JSON string
?>
This script starts by initializing a variable and assigning an associative array that contains student information. The variable $students is then passed to a function called json_encode(), which converts the variable into JSON string. When this script is run, it generates a valid response that can be exposed as JSON data feed for other applications to utilize.
The output is as follows:
{
"id": 101,
"name": "John Doe",
"isStudent": true,
"scores": [40, 50],
"courses":
{
"major": "Finance",
"minor": "Marketing"
}
}
We have successfully generated our first JSON feed via a simple PHP script; let us take a look at the method to parse JSON that comes in via an HTTP request. It is common for web applications that make asynchronous HTTP requests to send data in JSON format:
$student = '{"id":101,"name":"John Doe","isStudent":true,"scores":[40,50],"courses":{"major":"Finance","minor":"Marketing"}}';
//Decoding JSON string into php array
print_r(json_decode($student));
The output is as follows:
Object(
[id] => 101
[name] => John Doe
[isStudent] => 1
[scores] => Array([0] => 40[1] => 50)
[courses] => stdClass
Object([major] => Finance[minor] => Marketing)
)
JSON implementation in Python
Python is a very popular scripting language that is extensively used to perform string operations and to build console applications. It can be used to fetch data from JSON API, and once the JSON data is retrieved it will be treated as JSON string. To perform any operations on that JSON string, Python provides the JSON module. The JSON module is an amalgamation of many powerful functions that we can use to parse the JSON string on hand:
import json
student = [{
"studentid" : 101,
"firstname" : "John",
"lastname" : "Doe",
## make sure we have first letter capitalize in case of boolean
"isStudent" : True,
"scores" : [40, 50],
"courses" : {
"major" : "Finance",
"minor" : "Marketing"
}
}]
print json.dumps(student)
In this example we have used complex datatypes, such as Tuples and Dictionaries, to store the scores and courses respectively; since this is not a Python course, we will not go into those datatypes in any depth.
The output is as follows:
[{"studentid": 101, "firstname": "John", "lastname": "Doe", "isStudent": true, "courses": {"major": "Finance", "minor": "Marketing"}, "scores": [40, 50]}]
The keys might get rearranged based on the datatype; we can use the sort_keys flag to retrieve the original order.
Now, let us take a quick look at how the JSON decoding is performed in Python:
student_json = '''[{"studentid": 101, "firstname": "John", "lastname": "Doe", "isStudent": true, "courses": {"major": "Finance", "minor": "Marketing"}, "scores": [40, 50]}]'''
print json.loads(student_json)
In this example, we are storing the JSON string in student_json, and we are using the json.loads() method that is available through the JSON module in Python.
The output is as follows:
[
{
u 'studentid': 101,
u 'firstname': u 'John',
u 'lastname': u 'Doe',
u 'isStudent': True,
u 'courses':
{
u 'major': u 'Finance',
u 'minor': u 'Marketing'
},
u 'scores': [40, 50]
}]