Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
JavaScript and JSON Essentials

You're reading from   JavaScript and JSON Essentials Build light weight, scalable, and faster web applications with the power of JSON

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher
ISBN-13 9781788624701
Length 226 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Sai S Sriparasa Sai S Sriparasa
Author Profile Icon Sai S Sriparasa
Sai S Sriparasa
Bruno Joseph D'mello Bruno Joseph D'mello
Author Profile Icon Bruno Joseph D'mello
Bruno Joseph D'mello
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Getting Started with JSON 2. The JSON Structures FREE CHAPTER 3. AJAX Requests with JSON 4. Cross-Domain Asynchronous Requests 5. Debugging JSON 6. Building the Carousel Application 7. Alternate Implementations of JSON 8. Introduction to hapi.js 9. Storing JSON Documents in MongoDB 10. Configuring the Task Runner Using JSON 11. JSON for Real-Time and Distributed Data 12. Case Studies in JSON 13. Other Books You May Enjoy

Languages that support JSON

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.

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:

This example is only intended to show you how JSON can be generated using PHP.
<?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

?>
To run a PHP script, we will need to install PHP. To run a PHP script through a browser, we will need a web server, such as Apache or IIS. We will go through the installation in Chapter 3, AJAX Requests with JSON, when we work with AJAX.

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:

This example is only intended to show you how JSON can be ingested into PHP.
$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:

This example is only intended to show you how JSON can be generated using Python.
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.

To run this script, Python2 needs to be installed. It comes preinstalled on any *nix operating system. Play with our code in Python with the following online executor: https://www.jdoodle.com/python-programming-online.

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:

This example is only intended to show you how JSON can be ingested into 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]
}]
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime