This article covers the basic concepts related to JSON, its relationship with JavaScript, and the use of JSON within an application.
What is JSON?
JSON is short for Javascript Object Notation. This is a textual format used to represent structured data using the notion of objects which are composed of a set of key-value pairs. Although it is a language neutral format, it is mostly used with Javascript because it is quite straightforward to serialize javascript objects into JSON format and the other way around.An ordinary object in JSON is constructed using multiple pairs of keys and values. In every single case, the keys are in strings while values may include: String , Number , Arrays , Booleans or even other objects. All of these key statutes are enclosed in a pair of curly braces "{ }" and each statute is separated from the other regulation by a comma. As an example here is a basic format for a JSON object:
Basic JSON Object Example
{"name": " "John","age":"30","isStudent" - false}
In this example:
- For example, "name" can be identified as the Key while "Jewelo's Shining" is the value for that key.
- "age" has the value of 30 and can also be defined as a key.
- While isStudent has a value of false
JSON Syntax Rules
A few essential elements must be maintained while creating a JSON code to operate it effectively and accurately:1. The object is always kept inside braces `{ }`.
2. Array is used to keep in Partnerhesis `[ ]` along with items that have multiple values.
3. Every Key is required to be a string enclosed inside double quotations i.e. `""`.
4. For every value: it can be either a boolean value, an array of strings, an object, a number or a null value.
5. Every Key- value pair has a relationship which is defined with a semi colon i.e. carved out with` : `.
You can find a more complicated JSON representation that contains arrays and objects:
Complex JSON Example
{ "name": "Alice","age": 25,"hobbies": ["reading", "hiking", "coding"],"address": {"street": "123 Maple St.","city": "Wonderland"}}
In this example, `hobbies` is an array and the other key called `address` is an object.
JSON to JS objects
When dealing with JSON in JavaScript, one of the major requirements is to transform JSON data into something that will be a JavaScript object and can be easily used. This is achieved using the `JSON.parse()` method which is provided by the language.The `JSON.parse()` method uses one parameter which is a JSON string and returns a suitable JavaScript object. We demonstrate the conversion of a JSON string to a JavaScript object in the snippet below:
Parsing JSON to JavaScript Object
let jsonString = '{"name": "Alice", "age": 25}';
let obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Alice
console.log(obj.age); // Output: 25
In the example above, the variable `jsonString` contains a string in a JSON format and enclosed in double quotes. The `JSON.parse()` approaches this string as a JavaScript object allowing `name` and `age` to be properties of an object.
How To Convert Javascript Objects Into Json Format
There are instances when a server needs to receive data from a JavaScript code, or say a file needs to be stored, either ways, the content must be converted to a JSON format. Certainly, this can be done by making use of `JSON.stringify()` function, that is converting a JavaScript object to a JSON object's string.With the following code, we will be able to apply the `JSON.stringify()` method.
Stringifying JavaScript Object to JSON
let person = {name: "Bob",age: 30,isStudent: false};
let jsonString = JSON.stringify(person);
console.log(jsonString); // Display: '{"name":"Bob","age":30,"isStudent":false}'
This way, the method `JSON.stringify` transforms a JavaScript `person` variable which is a javascript object into a string in json format that can be sent to a server or saved within a file.
Retrieving And Sending JSON Objects Through Web Apps
In web development it won't be a surprise to say that APIs, that is Application Programming Interfaces, are all over and they tend to receive and transmit data in a JSON format. Although, it does seem rather common such as making an asynchronous request to a server.One common way of retrieving JSON data is by using the `fetch()` function, which is an asynchronous request and returns a promise. Here is an instance of fetching a JSON data and utilizing it:
Fetching JSON Data Example
fetch("https://api.example.com/data")
.then(response => response.json()) // A method that converts the response body// as JSON, which is a response format to // note as well
.then(data => {
console.log(data); // Add user defined logic
})
.catch(function (error){
console.log("Error: " + error);
});
In this example, notice the following:
- An HTTP request is executed through the use of the `fetch()` function which passes the designated URL.
- In the `response`, JSON data is parsed and retrieved through the use of the `response.json()` method.
- A Javascript object is also retrieved in the form of a resultant object assigned to the variable 'data'.
- This object can now be used for further manipulating, editing, or displaying.
Manipulating JSON in Javascript on the Server-Side
In fact, javascript isn't limited to the client-side only. Node.js is one alternative where JavaScript handles the server-side client requests. Just like client-side java script, when using JavaScript server-side APIs or working with databases, JSON is also crucial. You may create, read or write JSON files in Node.js utilizing the built-in `fs` (file system) module.Let's learn how to read and write JSON data with the `fs` module in Node.js with help of the following example:
Reading and Writing JSON in Node.js
const fs = require('fs');
// Reading JSON from a file
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) {
console.log(err);
return;
}
let jsonData = JSON.parse(data); // Converts JSON string into JavaScript object
console.log(jsonData);
});
// Writing JSON to a file
let newPerson = { name: "Charlie", age: 28 };
fs.writeFile('newData.json', JSON.stringify(newPerson), 'utf8', (err) => {
if (err) {
console.log(err);
} else {
console.log("Data has been written to the file.");
}
});
In this case:
- The `fs.readFile()` function takes the JSON data from a file and `JSON.parse()` function converts the JSON string data into JavaScript objects.
- `fs.writeFile()` function saves a file in which the JavaScript object is transformed into a JSON string using `JSON.stringify()`.