JSON – Advantages and Disadvantages

Back to Blog
JSON versus XML - JSON web service php

JSON – Advantages and Disadvantages

JSON (JavaScript Object Notation) is light-weighted designed such that humans can easily read data interchange and its execution.

The JSON format was originally specified and developed by Douglas Crockford and is described in RFC 4627 license. The JSON filename extension is .json.

JSON is based on the object notation of the JAVASCRIPT language and its standard only. It does not require JavaScript to read or write because it is made in text format which is language independent and can be run everywhere. JSON notation contains these basic elements which have JSON advantages in JAVASCRIPT:

1. Objects:Objects begin and end with curly braces ({}).

2. Object Members: Members consist of strings and values commas(,) separated

3. Arrays: Arrays begin and end with braces and contain different values.

4. Values:A value can be a string, can be an object, an array, or the literals

5. Strings:Strings are surrounded by double quotes and contain the Unicode colon (:). Members are separated by commas(,).Values are separated by commas(,). true, false or null.character or common backslash escapes.

JSON Example

{
  "first_name": "Rajeev",
  "last_name": "Sharma",
  "email_address": "rajeev@ezeelive.com",
  "is_alive": true,
  "age": 30,
  "height_cm": 185.2,
  "billing_address": {
    "address": "502, Main Market, Evershine City, Evershine, Vasai East",
    "city": "Vasai Raod, Palghar",
    "state": "Maharashtra",
    "postal_code": "401208"
  },
  "shipping_address": {
    "address": "Ezeelive Technologies, A-4, Stattion Road, Oripada, Dahisar East",
    "city": "Mumbai",
    "state": "Maharashtra",
    "postal_code": "400058"
  },
  "phone_numbers": [
   {
   "type": "home",
   "number": "9975666694"
   },
   {
   "type": "office",
   "number": "9822117730"
   }
 ],
 "date_of_birth": null
}

JSON Advantages

1. JSON is Faster:

JSON syntax is very easy to use. We have to use only -> as a syntax which provides us an easy parsing of the data and faster execution of the data. Since its syntax is very small and light weighted that’s the reason that it executes the response in the faster way.

2. Schema Support:

It has the wide range of supported browser compatibility with the operating systems so the applications made with the coding of JSON doesn’t require much effort to make it all browser compatible. During development, the developer thinks for the different browsers but JSON provides that functionality.

Ezeelive Technologies - Rest API Security
Rest API Security – How secure JSON data transfer

3. Server Parsing:

On the server side parsing is the important part that developers want if the parsing will be fast on the server side then the only user can get the fast response of their response so in this case JSON server-side parsing is the strong point that indicates us to use the JSON on the server side.

4. Tool for sharing data:

JSON is the best tool for the sharing data of any size even audio, video etc. This is because JSON stores the data in the arrays so data transfer makes easier. For this reason, JSON is a superior file format for web APIs and for web development.

JSON Disadvantages

First and foremost, in JSON has no error handling for JSON calls. If the dynamic script insertion works, you get called and will get the response perfectly.

If not inserted, nothing happens. It just fails silently. For example, you are not able to catch a 404 error from the server, Nor can you cancel or restart the request. You can, however, timeout after waiting a reasonable amount of time.

Another major drawback of JSON is that it can be quite dangerous if used with untrusted services or untrusted browsers, because a JSON service returns a JSON response wrapped in a function call, which will be executed by the browser if it will be used with untrusted browser it can be hacked, this makes the hosting Web Application Vulnerable to a variety of attacks.

If you are going to use JSON services, it’s very important to be aware of the threats which JSON have in that and also be aware of the things which can protect it. JSON only have limited supported tools which we can use during JSON development.

JSON vs BSON

JSON (JavaScript Object Notation) and BSON (Binary JSON) are both data interchange formats used to represent structured data in a human-readable and machine-readable way. However, they have some key differences:

Key PointsJSONBSON
Serialization Format
JSON is a text-based format. It uses plain text to represent data using a combination of key-value pairs, arrays, and primitive data types like strings, numbers, booleans, and null. JSON is easy for humans to read and write.BSON, on the other hand, is a binary format. It encodes data in a compact binary form, which is more efficient for storage and transmission but not human-readable like JSON.
Efficiency
JSON is less efficient in terms of size and performance compared to BSON. JSON data is typically larger in size because it includes human-readable whitespace and uses a text-based representation.BSON is more efficient in terms of both size and parsing performance. It is designed to be compact and can be parsed more quickly by machines.
Data Types
JSON supports a limited set of data types, including strings, numbers, booleans, arrays, objects, null, and nested combinations of these types.BSON supports a wider range of data types, including additional data types like dates, binary data, and specific numerical types. This makes BSON more suitable for representing data in some programming languages with richer type systems.
Extensibility
JSON is a well-defined standard with a fixed set of data types. Extending JSON typically involves adding custom fields or using conventions within the data itself.BSON allows for more flexibility in extending the data format by supporting additional data types, which can be useful for representing data in certain contexts.
Use Cases
JSON is commonly used for data interchange between web services, configuration files, and settings where human readability is important. It is widely supported in various programming languages.BSON is often used in situations where performance and compactness are critical, such as in databases like MongoDB, which uses BSON as its native storage format.
Example
{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "courses": ["Math", "History", "Science"]
}
\x16\x00\x00\x00
\x02hello\x00\x06\x00\x00\x00world\x00
\x00

JSON is a widely used text-based data format that is human-readable and easy to work with in many programming languages. BSON, on the other hand, is a binary format that is more efficient in terms of size and parsing speed, making it suitable for specific use cases where performance and compactness are priorities, such as in certain database systems. The choice between JSON and BSON depends on the specific requirements of your application.

JSON vs XML

JSON and XML (Extensible Markup Language) are both data interchange formats used to represent structured data, but they have different characteristics and are used in various contexts. Here’s a comparison of JSON and XML:

Key PointsJSONXML
Syntax
JSON uses a simple and compact syntax with key-value pairs. It is easier for humans to read and write due to its minimalistic and less verbose structure.XML uses a more complex markup language with tags and attributes, which can make it more verbose and harder for humans to read and write.
Data Types
JSON supports basic data types such as strings, numbers, booleans, arrays, objects, and null values. It represents data in a hierarchical manner.XML is more flexible in terms of defining custom data types through Document Type Definitions (DTD) or XML Schema Definitions (XSD). It can represent data in a hierarchical structure as well.
Readability
JSON is generally considered more readable by both humans and machines due to its concise and straightforward syntax.XML can be less readable for humans because of its tag-based structure and verbosity.
Size Efficiency
JSON is usually more compact in terms of data size compared to XML. This can be advantageous in situations where bandwidth or storage is limited.XML tends to be more verbose, which can result in larger file sizes compared to JSON representations of the same data.
Parsing and Processing
JSON is typically faster to parse and process because of its simpler structure. Most programming languages have efficient JSON parsers.XML parsing can be more resource-intensive due to its complex and extensible nature, especially when using DTDs or XSDs.
Schema Validation
JSON does not have built-in schema validation, but it can be validated using external tools or libraries.XML can be validated against predefined schemas using DTD or XSD, ensuring data conformity.
Namespace Support
JSON does not natively support namespaces, which can be important in certain XML use cases.XML supports namespaces, making it suitable for scenarios where data needs to be uniquely identified in a complex hierarchy.
Use Cases
JSON is commonly used for web APIs, configuration files, and data exchange between modern web applications and services. It’s well-suited for representing structured data.XML is often used in contexts where data needs to be highly structured, self-descriptive, or validated against a schema. It’s prevalent in document-oriented applications, including publishing, finance, and some legacy systems.

JSON and XML are both useful data interchange formats, but JSON is generally preferred for modern web development and API integration due to its simplicity, readability, and efficient parsing. XML is still relevant, particularly in scenarios where complex data structures, document hierarchies, or specific standards and namespaces are required. Your choice between JSON and XML should depend on your project’s specific requirements and the ecosystem you are working in.

JSON vs YAML

JSON and YAML (YAML Ain’t Markup Language) are both data serialization formats used for representing structured data. They serve similar purposes but have some differences that make each suitable for different use cases. Here’s a comparison of JSON and YAML:

Key PointsJSONYAML
Syntax
Uses a simple and strict syntax with key-value pairs separated by colons (:), arrays represented with square brackets ([]), and objects (associative arrays) represented with curly braces ({}). JSON is easy for machines to parse but less human-readable due to the use of punctuation.Employs a more human-readable, indentation-based syntax that uses colons and spaces. YAML uses whitespace and indentation to define the structure of data, which makes it more intuitive for humans but can lead to formatting issues if not used consistently.
Readability
While JSON is machine-friendly and widely supported, its strict punctuation-based syntax can be less readable for humans, especially for complex nested structures.YAML is designed with human readability in mind. Its indentation-based structure is more natural to read and write for humans, which makes it a good choice for configuration files and documents.
Complexity
Well-suited for representing simple to moderately complex data structures. It excels at representing data in key-value pairs and arrays.Can handle complex data structures with ease due to its nested, hierarchical nature. It is especially useful for representing configuration files with deep nesting.
Comments
Does not support comments within the data itself. Comments are typically placed in separate documentation.Supports comments using the # symbol, allowing you to include explanatory notes directly within the data.
Data Types
Supports basic data types, including strings, numbers, booleans, null, arrays, and objects. It doesn’t have native support for binary data.Supports basic data types similar to JSON, including strings, numbers, booleans, null, and arrays. Additionally, YAML has more flexible handling of data types and allows custom data types to be defined.
Usage
Commonly used for data interchange in web APIs, configuration files, and data storage. It’s also used in NoSQL databases and JavaScript-based applications.Frequently used for configuration files, data serialization in configuration management tools (e.g., Ansible and Kubernetes), and human-readable data storage.
Compatibility
Supported by a wide range of programming languages, making it easy to work with JSON data in various environments.While well-supported in many programming languages, YAML parsers and libraries may not be as prevalent as those for JSON.

JSON and YAML both have their strengths, with JSON being a good choice for machine-to-machine communication and data interchange, while YAML excels in human-readable configuration files and documents. The choice between them should depend on your specific use case and the balance between machine-friendliness and human-friendliness that your project requires.

JSON vs JSONB

JSON and JSONB (JSON Binary) are both data storage formats used in relational databases, but they have distinct differences in how they store and manage JSON data. Here’s a comparison of JSON vs. JSONB:

Key PointsJSONJSONB
Data Storage
In a relational database, JSON data is stored as text in a structured column. While JSON is human-readable and flexible, it requires parsing when querying or updating specific elements within the JSON structure.JSONB stores JSON data in a binary format, which is optimized for efficient storage and retrieval. It uses a compact binary representation that allows for fast indexing and querying of specific JSON elements.
Performance
Retrieving specific elements from JSON data can be slower because the database needs to parse the entire JSON document to access the requested data.JSONB is designed for performance. It provides faster query performance, especially when you need to search or index specific JSON attributes. This is because JSONB stores the data in a more efficient binary format.
Size
JSON data is typically larger in size compared to JSONB due to its human-readable text representation.JSONB data is smaller in size because it uses a binary format, making it more space-efficient.
Querying and Indexing
While relational databases often provide functions and operators for querying JSON data in columns, the performance may be suboptimal for complex queries, especially on large datasets.JSONB allows for efficient indexing of specific JSON elements, enabling complex queries to perform better. This makes JSONB suitable for scenarios where you need to search or filter data within JSON documents.
Validation and Constraints
JSON data may not enforce strict validation or constraints on the structure of JSON documents, allowing for potentially invalid or inconsistent data to be stored.JSONB doesn’t enforce validation or constraints either, but it implicitly validates the stored JSON data during conversion to its binary format. This means that JSONB data is always well-formed JSON.
Data Modification
Modifying specific elements within a JSON document can be more complex and requires parsing and updating the entire document.JSONB allows for efficient updates of specific elements within a JSON document because it doesn’t need to rewrite the entire binary representation.
Use Cases
JSON is often used when the human readability of the JSON data is important, and the data doesn’t need to be frequently queried or indexed.JSONB is recommended when performance, efficient querying, and indexing of JSON data are essential, especially in scenarios where you have large volumes of JSON data in a relational database.

The choice between JSON and JSONB in a relational database depends on your specific requirements. JSONB is generally favored for scenarios where query performance, efficient indexing, and storage space are important, while JSON is more suitable when human readability of the data is a priority and performance is less critical.

How to secure data and prevent JSON Vulnerability & Hijacking

Secure data prevent json vulnerability hijacking
JSON prevent Cross Site Request Forgery (CSRF)

JSON is not fully secure as we think in the web world, Cross Site Request Forgery (CSRF) in JSON Array hack allow grab sensitive user data from an unsuspecting user.

This is major in exposing a JSON service which contains JSON array, sensitive data, responds to GET requests, Request with JavaScript enabled, request supports the __defineSetter__ method etc.

In Above we had discussed the issue, Now will discuss how to prevent CRSF Attack and Secure sensitive data in following points:

  1. Most important, All the request method has to be POST and Prevent your code to accept only POST Request.
     $.ajax ({
        url: '//yourdomainname.com/login',
        dataType: 'json',
        data: JSON.stringify(dataObject),
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        success: function (jsonData) {
            // Success callback
        },
        error: function() {
            //any error to be handled
        }
     });
    
  2. Add unique CSRF token in request prevent the application from cookie hijacking and bad requests.
  3. Always use secure transfer protocol (HTTPS) in requests.
  4. Check special header such as the X-Requested-With: XMLHttpRequest or Content-Type: application/json before serving the response to the request.
  5. Code testing tools like checkmarx, SonarQube, Burp Suite etc. will help to application security.
  6. User Access log should be managed to check which user activities.
  7. Use API and End URL authentication to validate current endpoint.
  8. Should use token-based API access such as JSON Web Tokens (JWT).
  9. Implement Error handling and Do not provide any technical detail in API call.
  10. JSON Validation: PHP 8.3 introduce built-in json validation function. It allows to check if a string is syntactically valid JSON, while being more efficient than json_decode():

PHP < 8.2

function json_validate(string $string): bool {
    json_decode($string);

    return json_last_error() === JSON_ERROR_NONE;
}

var_dump(json_validate('{ "data": { "name": "nitin" } }')); // true

PHP 8.3

var_dump(json_validate('{ "data": { "name": "nitin" } }')); // true

Example of JSON Web Service PHP with MySQL

MySQL Database :

create database IF NOT EXISTS `ezeelive_json_rest_tutes`

--
-- Table structure for table `customer`
--

CREATE TABLE IF NOT EXISTS `customer` (
`customer_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email_address` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`is_active` text NOT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO `customer` (`customer_id`, `first_name`, `last_name`, `email_address`, `password`, `is_active`) VALUES
(1, 'Rajeev', 'Sharma', 'rajeev@ezeelive.com', 'e10adc3949ba59abbe56e057f20f883e', 1),
(2, 'Nitin', 'Bhardwaj', 'nitin@ezeelive.com', '6d071901727aec1ba6d8e2497ef5b709', 0);

config.php

<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('ezeelive_json_rest_tutes', $conn);

json_rest_customer_list.php

<?php
include_once('config.php');
$result = mysql_query("SELECT customer_id, first_name, last_name, email_address, is_active FROM `customer` ORDER BY customer_id ASC;");
if(isset($result))
{
$data =array();
while($d = mysql_fetch_array($result)){
extract($d);
$data[] = array("customer_id" => $customer_id, "first_name" => $first_name, "last_name" => $last_name, "email_address" => $email_address, "is_active" => $is_active);
}
$json = array("status" => 1, "info" => $data);
}else{
$json = array("status" => 0, "msg" => "An error occurred.");
}
@mysql_close($conn);

// Output json header
header('Content-type: application/json');
echo json_encode($json);

JSON Output:

{
status: 1
  info: [2]
    0:{
     customer_id: "1",
     first_name: "Rajeev",
     last_name: "Sharma",
     email_address: "rajeev@ezeelive.com",
     is_active: "1"
     },
    1:{
     customer_id: "2",
     first_name: "Nitin",
     last_name: "Bhardwaj",
     email_address: "nitin@ezeelive.com",
     is_active: "0"
     }
}

Google Trends Report

Conclusion

As we saw many technologies here we come to end with some good and some bad parts about is so same also happening with the JSON.

It also have its advantages and disadvantage, like if you except a quick and perfect response from the server then you can refer it, it has the wide range of schema supported with that but to use that we the device should be on the trusted network otherwise meanwhile it can make a problem for yourself only.

Share this post

Comments (3)

  • Kenneth Kasajian Reply

    Recently after having drunk the JSON Kool-Aid, I needed to create a configuration file for one of our applications. This is the kind of thing I would ordinarily use an .ini file or .xml. Having never been a fan of XML (like ever!) I thought, JSON would be a great choice for configuration files. Considering the fact it’s used that way by many programming tools, I figure that sounds like a reasonable choice.

    Well, I regret that decision. This specific configuration file has many places where the user would have to type in a file path. Now they have to type two backslashes for every backslash. Try explaining that to an end-user. Even those who regularly edit the Windows registry will wtf @ that one. And before you think this is a Windows-only issue, it’s not just backslash. According to the JSON spec, the forward-slash character also must be escaped with a backslash. It’s bad enough that JSON requires keys to be quoted when they don’t need to be, but the escaping of strings is just an unnecessary complexity for users.

    I realize the JSON fan-boys will say that if it’s too complicated for the use, then you should create a UI. I’m really not buying that argument. I can’t believe I’m saying this, but XML would have been a better option.

    November 21, 2014 at 6:08 pm
  • Shawn Reply

    I’m not sure how the disadvantges are because of the json format? If you are saying that ajax calls cant return errors or handle errors you are not correct.

    November 21, 2014 at 6:20 pm
  • Kenneth Reply

    I don’t see the disadvantage really, basically the improper data handling is the problem and not an error. Try having zero fill or default and it will be gone.

    November 25, 2014 at 5:44 am

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Blog