Understand and Learn javascript JSON Object with examples
- Admin
- Dec 31, 2023
- Javascript
JSON
is abbreviated as JavaScript object notation.
Let us first understand what is JSON type?
What is JSON ?
JSON
is a text-based file format that is used to save and transfer data between software applications. Usually, the browser sends the request data to the server and receives the response data in JSON format.JSON
is simple to read and lightweightJSON
is language-independent. All the programming languages have the support for understandingJSON
notation- It only represents data in this format, No methods and functions are supported.
- Comments are not allowed in the data
JSON
Sample
[
{
"name": "Tom",
"id": "1",
"age": 25
},
{
"name": "Ram",
"id": "2",
"age": 35
}
]
JSON Syntax:
The JSON object is similar to JavaScript Object syntax.
JSON object holds key and value pairs separated by a colon. Each object contains both key and value pairs, separated by a comma.
A JSON array represents using brackets which holds a list of similar elements
Keys only accept Strings, and numbers, but not arrays or object arrays
Values can be number, Arrays, String, Objects, boolean, null
Here is a Simple JSON example
var emp = { name: "Tom" };
JSON Array Example :
var emp = [{ name: "John" }, { name: "Ram" }];
JSON Files:
JSON data can be represented in the form of Strings as well as files. The file extension is json
. And content type for these files is application/json
.
javascript JSON object
The JSON object is used to manipulate JSON format-based files and strings. we can convert to/from a string using this method.
There are only two methods available in JavaScript.
JSON.parse() method
Take the input as a string and returns the object.
Syntax:
JSON.parse(stringObject\[, reviver\])
Arguments-
stringObject is a string to parse as JSON
reviver - is called during transformation to manipulate key and values and return it. The return value is the object.
Examples The below are valid strings for parsing into a JavaScript object.
var jsonString = '{"name": "John","id": "1","age": 25}';
var jsonObject = JSON.parse(jsonString);
console.log(typeof jsonString); // returns string
console.log(typeof jsonObject); // returns object
console.log(jsonString); // returns {"name": "John","id": "1","age": 25}
console.log(jsonObject); // returns Objectage: 25id: "1"name: "John"__proto__: Object
console.log(jsonObject.name); // returns John
// valid json parsing
JSON.parse("{}"); // returns {}
JSON.parse('"hello"'); // returns "hello"
JSON.parse("null"); // returns null
JSON.parse("false"); // returns false
json parse example for string reviver
The below example parses the JSON string and convert the value to Uppercase if the value type is a string.
var test = JSON.parse('{"name":"kiran"}', (key, value) => {
return typeof value === "string"
? value.toUpperCase() // return value in uppercase
: value; // return everything else unchanged
});
console.log("t", test); // returns json object like {"name":"KIRAN"}
JSON parse SyntaxError Example throws Syntaxerror when unable to parse string format to a JSON object.
Uncaught SyntaxError: Unexpected token ] in JSON at position
JSON.parse("[4, 1, 9, ]");
JSON.parse('{"key" : "value", }');
Solution or fix to check JSON string format and fix it. You can also check online JSON format validation tools
to validate it if required.
JSON Stringify method
stringify
method is used to serialize JSON values as JSON strings.
Syntax:
JSON.stringify(jsonvalue\[, replacer\[, space\]\])
Arguments:
- jsonvalue - value converted to JSON string
- replacer - is a function written to filter/values from the full JSON string. keys/values can be omitted using this function. This is optional.
- spacer - the third argument can be string or number
And the return value is a JSON string
Throws a TypeError (“cyclic object value”) exception when a circular reference is found. Valid JSON stringify example
const arrayJson = ["kiran", "john", "frank"];
const stringArrayJson = JSON.stringify(arrayJson);
console.log(stringArrayJson); // return ["kiran","john","frank"]
JSON stringify reviver and space example:
const employeeString = {
id: 1,
name: "Kiran",
age: 35,
};
function replacer(key, value) {
console.log(typeof value);
if (key === "age") {
return undefined;
}
return value;
}
const empJsonString = JSON.stringify(employeeString, replacer);
console.log(empJsonString); // returns {"id":1,"name":"Kiran"}
const empJsonString1 = JSON.stringify(employeeString, null, "--");
console.log(empJsonString1); // returns {--"id": 1,--"name": "Kiran",--"age": 35}
JSON stringify TypeError error we are going to use stringify for the circular reference use case where parent and child objects are referenced. Uncaught TypeError: Converting circular structure to JSON
const parentObject = { childObject: null };
parentObject.childObject = parentObject;
JSON.stringify(parentObject);
Difference between json and jsonp types
JSON | JSONP |
---|---|
Plain JSON | JSON with padding, JSON data + function call |
It works with transferring data from the client and server from the same domain. | get the data from a server from a different domain |
Content type is application/json | The content type is application/javascript . |
{ "name": "Tom" } | function({ "name": "Tom" }) |
Easy to use and consume it | Not simple to understand and use it |
How to read data from JSON files in javascript?
Reading data from JSON files is similar to retrieving data from the Ajax API Call. we can achieve this using XMLHttpRequest or ajax jquery call
Steps
- Create XMLHttpRequest object
- Handles onreadystatechange event- this will be called whenever status changed
- readyState state is 4 and status is 200, request successfully connected and a successful response is returned
- parse data using the JSON parse method
- onError event is used to handle the errors.
- open and send methods are used to connect to the resource and send the request to the server.
getJSONFileData: function() {
// XMLHttpRequest read json example
const xmlRequest = new XMLHttpRequest();
xmlRequest.overrideMimeType("application/json");
let path = 'file:///C:/myproject/tsconfig.json';
xmlRequest.open('GET', path, true);
xmlRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const files = JSON.parse(xmlRequest.response);
} else {
console.log('Returned an error while reading json from file');
}
};
xmlRequest.onerror = function() {
console.log('Error occured during XMLHttpRequest');
};
xmlRequest.send();
}
Another to read json objects with AJax consume REST API or file
// ajax read json example
$.ajax({
url: "file:///C:/myproject/tsconfig.json",
dataType: "json",
method: "GET",
success: function (response) {
data = JSON.parse(response);
console.log(data);
},
});