Skip to content
-
How to Parse JSON Data in JavaScript?
Last Updated :
23 Jul, 2025
To parse JSON data in JavaScript, you can use the JSON.parse() method. This method converts a JSON string into a JavaScript object, making it easier to work with the data.
1. Parse Simple JSON Strings
JavaScript
//Driver Code Starts
const jsonS = '{"name": "Rahul", "age": 25, "city": "Mumbai"}';
//Driver Code Ends
const obj = JSON.parse(jsonS);
//Driver Code Starts
console.log(obj.name);
//Driver Code Ends
- The string is in JSON format.
- JSON.parse() converts it into a JavaScript object.
- You can access the object properties using dot notation or brackets.
2. Parse JSON Array Strings
JavaScript
//Driver Code Starts
const jsonA = '[{"name": "Anjali"}, {"name": "Vikas"}]';
//Driver Code Ends
const a = JSON.parse(jsonA);
a.forEach(person =>
console.log(person.name));
- The JSON string represents an array of objects.
- After parsing, you can iterate through the array and access each object.
3. Parse Nested JSON
JavaScript
//Driver Code Starts
const nested = '{"person": {"name": "Ravi", "address": {"city": "Delhi", "pin": 110001}}}';
//Driver Code Ends
const obj = JSON.parse(nested);
console.log(obj.person.address.city);
- JSON.parse() handles nested objects seamlessly.
- You can access nested properties using chained dot notation.
4. Parse JSON with Validation
JavaScript
//Driver Code Starts
const jsonS = '{"name": "Pooja", "age": 28}';
//Driver Code Ends
try {
const obj = JSON.parse(jsonS);
console.log(obj);
} catch (e) {
console.error("Invalid JSON:", e.message);
}
Output{ name: 'Pooja', age: 28 }
- Wrapping JSON.parse() in a try...catch block handles invalid JSON inputs.
- This is especially useful when dealing with external or unverified data.
5. Parse JSON with a Reviver Function
JavaScript
//Driver Code Starts
const jsonS = '{"name": "Amit", "age": "30"}';
//Driver Code Ends
const obj = JSON.parse(jsonS, (key, value) => {
if (key === "age") return parseInt(value);
return value;
});
//Driver Code Starts
console.log(obj.age);
//Driver Code Ends
- A reviver function lets you transform values during parsing.
- Here, the age is converted from a string to a number.
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}