JSON and its introduction
JSON
- is the abbreviation of “JavaScript Object Notation”
- is a lightweight data interchange format.
It is a text-based format used for
- storing and exchanging data between a server and a client
- as well as between different parts of an application.
JSON is ~
- easy for humans to read and write,
- easy for machines to parse and generate.
Usage -
It is often used for configuration files, data storage, and communication between a web server and a web client, among other applications.
Lets explore about JSON
JSON data is represented as key-value pairs
where keys are strings enclosed in double quotes, followed by a colon, and then the associated value.
The value can be a ~
- string
- number
- boolean
- null
- another JSON object
- or an array
and these comes under JSON Syntax.
Lets explore an example of JSON data:
{
"name": "Malti Sharma",
"age": 30,
"isStudent": false,
"gender": "female",
"hobbies": ["reading", "gardening", "traveling", "poetry"]
}
In the above example, the JSON object has five key-value pairs:
- “name” with the string value “Malti Sharma"
- "age” with the number value 30
- ”isStudent” with the boolean value false
- ”gender” with the string value “female"
- "hobbies” with an array value containing four strings.
JSON and its Advantages
- Uses a fewer number of standardized Syntax.
- More Self-describing (readable by humans and machines).
- JSON Properties and values can be accessed immediately by using JavaScript.
- JSON uses arrays and Objects.
- Code for parsing and interchanging JSON data is readily available in almost all modern programming languages.
- Hierarchical (values can contain a list of objects or values).
- Unlike Javascript, JSON can retrieve values from anywhere as it supports all languages.
JSON Usage
- Transfers data between a server and various web applications.
- Performs asynchronous data calls without requiring a page refresh. This is widely used for asynchronous browser/server communication
- APIs and web services use JSON to transfer real-time sensitive data.
- Compiles user data for local storage.
- JSON is now being supported by almost all Programming languages.
- JSON supports for sending, reading, and receiving texts available in all the real-world business.
- JSON-RPC is a Remote Procedure call (RPC) protocol built on JSON, which allows system to send multiple notifications to the server.
JSON Vs XML
Properties | JSON | XML |
---|---|---|
Abbreviation | Javascript Object Notation | eXtensible Markup Language |
Data Representation | Uses a lightweight, human-readable format that is based on key-value pairs. Data is represented using objects (curly braces {}) and arrays (square brackets []). | Uses a markup language with a more verbose and hierarchical structure. Data is enclosed in tags, often resembling an HTML structure with opening and closing tags. |
Readability | Generally considered more readable by humans due to its simpler syntax and lack of excessive markup. | Can be more verbose and harder to read due to the presence of tags and attributes. |
Parsing | Easier and faster to parse in JavaScript and many other programming languages because it maps directly to data structures like dictionaries and lists. | Requires more complex parsing, often involving the use of XML parsers and libraries. |
DataTypes | Supports a limited set of data types, including strings, numbers, booleans, null, objects, and arrays. | Allows for more complex data types and custom data structures through the use of schemas. |
Size | Generally produces smaller payloads compared to XML due to its concise syntax. | Tends to produce larger data payloads because of the additional markup. |
Usage | Commonly used in web APIs, configuration files, and data interchange in JavaScript-based applications and RESTful web services. | Historically used in web services (SOAP), document storage (e.g., RSS, XHTML), and data interchange in various domains, including finance and healthcare. |
Schema Validation | Supports schema validation through technologies like JSON Schema, but it’s not as widely adopted as XML schemas. | Has robust support for schema validation through technologies like Document Type Definitions (DTD) and XML Schema Definition (XSD). |
JSON and Limitations
- JSON cannot handle large data.
- Not suitable for handling different multimedia formats.
- JSON does not have a feature to support ‘comments’.
JSON Syntax and Rules
Rules ~
- Keys must necessarily be strings, written with double quotes.
- Data can be a Name/value pairs that consist of a field name inside double quotes, followed by a colon, and then by a value inside double quotes
- Example:“Name”:“Pete”
- Data must be separated by Commas (,).
- Example: “Rama”, “Pete”
- Curly brackets {} to hold objects
- Example: { “Name”:“Josephine” }
- Square brackets [] hold arrays
- Example: {“employees”:[ “Rama”, “Pete”, “Josephine” ]}
Invalid DataTypes - JSON
JSON values cannot use any of the following data types:
- function
- date
- Undefined
JSON is built on two important structures:
- Object - A collection of name/value pairs.
- Array - An ordered list of values. An array could be a combination of multiple objects.
JSON Parse
// A JSON string representing an object
var jsonString = '{"name": "Johny Ryan", "age": 30, "city": "New York"}';
// Parse the JSON string into a JavaScript object
var jsonObject = JSON.parse(jsonString);
// Access values in the JavaScript object
console.log("Name:", jsonObject.name); // Output: Name: Johny Ryan
console.log("Age:", jsonObject.age); // Output: Age: 30
console.log("City:", jsonObject.city); // Output: City: New York
JSON parsing refers to the process of
- converting a JSON (JavaScript Object Notation) string into a data structure that can be used in a programming language.
Parsing JSON is a common task when working with data received from a web server, reading configuration files, or processing data in JSON format.
- JSON.parse() function was developed as a safer alternative to eval.
While receiving data from the web server, the data is always in the string format, we have to parse the data with JSON.parse() and the data becomes a JavaScript object.
JSON Stringify
// A JavaScript object
var person = {
name: "Johny Ryan",
age: 30,
city: "New York",
};
// Convert the JavaScript object into a JSON-formatted string
var jsonString = JSON.stringify(person);
// Display the JSON string
console.log(jsonString);
Output :
{ "name": "Johny Ryan", "age": 30, "city": "New York" }
- JSON.stringify() is a method used in JavaScript to convert a JavaScript object or value into a JSON-formatted string.
- This is the opposite operation of JSON parsing, which involves converting a JSON string into a JavaScript object.
- JSON.stringify() is commonly used when you want to send data to a server, store data in a file, or transmit data between different parts of a web application.
JSON and its Family Libraries
Apart from the regular JSON, we have other versions of JSON in use as well.
-
Google’s GSON - Java library from Google to convert Java Objects into JSON and vice versa. In addition, it paves room for simpler implementation by not requiring to annotate your classes.
-
Oracle’s JSONP is Java API for JSON processing. This consumes/produces streaming JSON text.
-
FasterXML’s Jackson - Can handle both JSON/non-JSON encodings. It is a set of data processing tools powered with streaming JSON parser and generator library.
JSON Security Concerns and Overcoming steps
-
Cross-Site Request Forgery (CSRF) ~
It is an exploit which takes advantage of a website trust in any user browser.
-
Cross-Site Scripting (XSS) attack ~
A type of injection attack that is injecting data into a web application to facilitate the execution or interpretation of malicious data that takes advantage of any normal website by a third party with a malicious script.
How to overcome these threats while using JSON
- Avoid using Top-level arrays which are valid JavaScript that can be linked to a script tag.
- Use HTTP POST instead of HTTP GET in JSON, because the GET request can be linked to any URL with a script tag which is a web threat.
- Use JSON.parse() instead of eval(), because eval() function will compile and execute any given set of string, which can open your code during web attacks, where JSON.parse() only parses JSON.
Summary
JSON has become a popular format for data exchange on the web as well as in other applications because of its simplicity, human-readability, and compatibility with many programming languages. It is widely used in RESTful APIs, AJAX requests, and configuration files for various software applications.