Book Image

JavaScript and JSON Essentials - Second Edition

By : Bruno Joseph D'mello, Sai S Sriparasa
Book Image

JavaScript and JSON Essentials - Second Edition

By: Bruno Joseph D'mello, Sai S Sriparasa

Overview of this book

JSON is an established and standard format used to exchange data. This book shows how JSON plays different roles in full web development through examples. By the end of this book, you'll have a new perspective on providing solutions for your applications and handling their complexities. After establishing a strong basic foundation with JSON, you'll learn to build frontend apps by creating a carousel. Next, you'll learn to implement JSON with Angular 5, Node.js, template embedding, and composer.json in PHP. This book will also help you implement Hapi.js (known for its JSON-configurable architecture) for server-side scripting. You'll learn to implement JSON for real-time apps using Kafka, as well as how to implement JSON for a task runner, and for MongoDB BSON storage. The book ends with some case studies on JSON formats to help you sharpen your creativity by exploring futuristic JSON implementations. By the end of the book, you'll be up and running with all the essential features of JSON and JavaScript and able to build fast, scalable, and efficient web applications.
Table of Contents (20 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

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:

Note

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

?>

Note

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:

Note

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:

Note

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.

Note

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:

Note

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]
}]