JSON Tutorial: Introduction for Beginners

JSON Tutorial

JSON (JavaScript Object Notion) is one of the most popular data transition formats. JSON originated in association with JavaScript.In the early 2000s, Douglas Crockford originally specified the JSON format. JSON is an open-standard, lightweight format and it’s a human-readable (It is easy for humans to read and write) also it is easy for machines to parse and generate. The JSON format used to serializing and transmitting structured data over the network. In this tutorial, you’ll learn the basic syntax of JSON and how to use JSON with JavaScript, PHP, and Python.

JSON filename extension: .json
JSON Internet Media type: application/json.

More details: https://www.json.org/

JSON example

JSON Tutorial
{
  "first name": "admin",
  "last name": "CtechF",
  "age": 24,
  "bodyear": 1995,
  "bodmonth": 6,
  "hasFacebookAccount": true,
  "hasTwitterAccount": false,
  "address": {
    "street address": "221b Baker St",
    "city": "Marylebone",
    "state": "London",
    "postal code": 10781,
    "country": "UK"
  },
  "phone numbers": [
    {
      "type": "home",
      "number": "121 123-1234"
    },
    {
      "type": "fax",
      "number": "575 456-4567"
    }
  ],
  "sex": {
    "type": "Male"
  }
}

View

view - style

Valid JSON Data Types

  • String
  • Number
  • Boolean
  • Object and Array
  • Null

JSON String

{
"field": "value"
}
{
  "first name": "admin",
  "last name": "CtechF",
  "email": "admin@ctechf.com"
}
view - style

JSON Number 

{
"field": value
}
{
  "age": 24,
  "bodyear": 1995,
  "bodmonth": 6
}
view - style

JSON Boolean

{
"field": True Or False
}
{
  "hasFacebookAccount": true,
  "hasTwitterAccount": false
}
view - style

JSON Object

{
"object": {
   "field1": "value",
   "field2": "value"
   .....
 }
}
{
  "address": {
    "street address": "221b Baker St",
    "city": "Marylebone",
    "state": "London",
    "postal code": 10781,
    "country": "UK"
  }
}
view - style

JSON Array

{
  "object": [
    {
      "field1": "value",
      "field2": "value"
       ....
    },
    {
      "field3": "value",
      "field4": "value",
       ....
    }
}
{
  "phone numbers": [
    {
      "type": "home",
      "number": "020 1234-1234"
    },
    {
      "type": "fax",
      "number": "0131 456-4567"
    }
  ]
}
view - style

or

{
  "object": 
   [
      "value1",
      "value2"
   ]
}
{
  "phone numbers": 
   [
      "020 1234-1234",
      "0131 456-4567"
   ]
}
view - style

JSON Null (empty type)

{
  "field": null
}
{
  "job": null
}
view - style

JSON Tutorial – JSON with JavaScript

What is JavaSctipt?

Javascript is a Programming Language for Web Development. It’s a client-side scripting language. it first appeared in 1995. There are similarities between Java and JavaScript, including name, syntax, and libraries.

Read more

Console output

JSON Tutorial - JavaScript

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>CtechF - JSON</title>
  <script src="index.js"></script>
</head>
<body>

</body>
</html>

index.js

var jsonDa = '{"name":"CtechF","email":"admin@ctechf.com","link":"https://ctechf.com","live": true,"startyear":2019,"tags":["technology","programming","json","python"]}';

var NewJSON = JSON.parse(jsonDa);
console.log(NewJSON);

Output

JSON Tutorial - JavaScript console

Exampleindex.html

<html>
   <head>
      <title>JSON with JavaScript</title>
      <script>
        var jsonDa = {"name":"CtechF","email":"admin@ctechf.com","link":"https://ctechf.com","startyear":2019, "live":true,"tags":["technology","programming","json","python","java"]}

        document.write("<h1>JSON with JavaScript</h1> <br>");
        document.write("<h3>Name: <i>" + jsonDa.name+"</i></h3>");
        document.write("<h3>Year: <i>" + jsonDa.startyear+"</i></h3> <br>");

        var live = jsonDa.live;
        if(live == 1) {
            document.write("<h3>Website Status: <i>Live</i></h3>");
        } else {
            document.write("<h3>Website Status: <i>Offline</i></h3>");
        }

        document.write("<h3>Tags: </h3>");

        var tagsLength = jsonDa.tags.length;
        for(i = 0; i<tagsLength; i++) {	
            document.write("<i>" +jsonDa.tags[i]);
            if(tagsLength != (i+1)) {
                document.write(" / ")
            }
            document.write("</i>")
         }
         

        document.write("<hr />");

        document.write("<p> Visit Now: <a href='"+ jsonDa.link + "'>https://ctechf.com</a></p>");
        document.write("<p> Contact me: <a href='mailto:"+ jsonDa.email + "'>" + jsonDa.email + "</a></p>");
      </script>
   </head>
   
   <body>

   </body>
</html>
view - style

Output

JSON Tutorial - JavaScript

You can request JSON data from the server – by using an AJAX request
Read more

JSON Tutorial – JSON with PHP

What is PHP?

PHP: Hypertext Preprocessor is a general-purpose server-side script language. it designed for web development. It designed by Rasmus Lerdorf in 1994 and first released in 1995. PHP is free to download and use. It can contain text, HTML, JavaScript, CSS and PHP code. PHP can do many things such as generate dynamic web pages, manage data in your database, control user access, etc… PHP 7 is much faster than the previous versions.

PHP 7 Tutorial: Introduction for Beginners (Basic)
PHP7 Tutorial | Part 2 – GET, POST and Cookies
PHP7 Tutorial | Part 3 – MySQL and PHP

Check this – Top 20 Programming Languages

Exampleindex.php

<?php
    $jsonDa = '{
        "name":"CtechF",
        "email":"admin@ctechf.com",
        "link":"https://ctechf.com"
    }';

    $data = json_decode($jsonDa);

    echo $data->name;  //CtechF
?>

Accessing JSON data from a URL

data.json

[{
	"name": "Deogo",
	"grade": "A"
}, {
	"name": "Jhon",
	"grade": "C+"
}, {
	"name": "Jehan",
	"grade": "B"
}, {
	"name": "Tony",
	"grade": "A+"
}]
view - style

index.php

<?php
    $url = 'data.json'; // Path of JSON file
    $jsonDa = file_get_contents($url);
    $datas = json_decode($jsonDa); // decode the JSON data

    foreach ($datas as $data) {
        echo $data->name . ': ';
        echo '<b>'. $data->grade . '</b><br>';
    }
?>
JSON Tutorial - PHP

Accessing JSON data from a URL – More

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON with PHP</title>

    <style>
        table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 20%;
        }

        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }
    </style>
    
</head>

<?php
    $url = 'data.json'; // Path of JSON file
    $jsonDa = file_get_contents($url);
    $datas = json_decode($jsonDa); // decode the JSON data
?>

<body>
    <table >
        <tbody>
            <tr>
                <th>Name</th>
                <th>Grade</th>
            </tr>
            <?php foreach ($datas as $data) : ?>
            <tr>
                <td> <?php echo $data->name; ?> </td>
                <td> <?php echo '<b>'. $data->grade . '</b><br>'; ?> </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>
JSON Tutorial - PHP

Converting a PHP data into JSON

<?php
    $data = [
        'name' => 'Tony',
        'grade' => 'A+'
    ];

echo json_encode($data);
?>
JSON Tutorial - PHP

JSON Tutorial -JSON with Python

What is Python?

Python is a scripting language and that is used for creating engineering-analysis tools, web development (server-side), software development, system scripting, and animation software. It designed by Guido van Rossum and first released in 1991. It’s an interpreted, High-level. General-purpose language. Python runs on Windows, Mac OS, and Linux.

Python Tutorial: Introduction for Beginners (Part 1)
Python Tutorial: Introduction for Beginners (Part 2)
SQL Tutorial: Introduction for beginners (Basic)
Python Tutorial: How to Connect MySQL Database in Python
Python Tutorial: Python GUI Programming (Tkinter)
Python Tutorial: Send Emails Using Python
Python Tutorial: Django Tutorial for Beginners
Python-Django Tutorial: Database and admin interface

import JSON

import json

jsondata.py

import json

jsonDa = '{"name":"CtechF","email":"admin@ctechf.com","link":"https://ctechf.com","startyear":2019, "live":true,"tags":["technology","programming","json","python","java"]}'

datas = json.loads(jsonDa)

"""
print(datas)
print(datas['name'])
print(datas['email'])
print(datas['live'])
print(tags = datas['tags'])
print(tags)
print(tags[2])

for tag in tags: 
    print(tag)

print(datas['link'])
"""
view - style

The results is a Python dictionary

JSON Tutorial - Python

Converting a Python data into JSON

jsonenc.py

import json

data = {
  "name": "Tony Padilla",
  "age": 18,
  "married": False,
  "children": False,
  "nickname": [
    {"name": "Tony", "by": "everyone" },
    {"name": "Unhelpful Yoda", "by": "clay"},
    {"name": "Tonio", "by": "family"}
  ]
}

print(json.dumps(data))

# sort the result
print(json.dumps(x, indent=4, sort_keys=True))
{"name": "Tony Padilla", "age": 18, "married": false, "children": false, "nickname": [{"name": "Tony", "by": "everyone"}, {"name": "Unhelpful Yoda", "by": "clay"}, {"name": "Tonio", "by": "family"}]}

{
    "age": 18,
    "children": false,
    "married": false,
    "name": "Tony Padilla",
    "nickname": [
        {
            "by": "everyone",
            "name": "Tony"
        },
        {
            "by": "clay",
            "name": "Unhelpful Yoda"
        },
        {
            "by": "family",
            "name": "Tonio"
        }
    ]
}
view - style

Sources : 
https://pixabay.com/ (images) 
https://jsoneditoronline.org/ (JSON Viewer)

Hello Friends,

Hope this post (JSON Tutorial: Introduction for Beginners) will help you to learn something, If you enjoy my work then please share my posts with your friends and anyone who might be interested in programming and don’t forget to subscribe my mailing list.

If you had any problem with this post, please do mention it in the comment section.

Like ctechf Facebook fan page: https://www.facebook.com/ctechf

Best Free eBooks to Learn Python Programming

python ebooks

Free eBooks to Learn Python, Here are 13 of the best Python eBooks for python lovers.
Download Now

How to be a Programmer

Liked it? Take a second to support CtechF on Patreon!

Leave a Reply

7 Shares
Share
Tweet
Share
Pin
Share