Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Read JSON File Using JavaScript
Next article icon

Read JSON File Using JavaScript

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JSON (JavaScript Object Notation) is a lightweight format used for storing and exchanging data. In JavaScript, there are multiple ways to read and parse JSON files. These methods can be used both in browser environments and in Node.js.

1. Using the fetch() API

The fetch() API retrieves JSON files asynchronously and parses them into JavaScript objects.

Syntax

fetch('sample.json')
.then(response => response.json()) // Parse JSON
.then(data => console.log(data)) // Work with JSON data
.catch(error => console.error('Error fetching JSON:', error));
  • Create a sample.json file with the desired data.
  • Use fetch("sample.json"), then parse the response with .json().
  • Handle the data or display it, using .catch() for errors.
HTML
<html> <head></head> <body>     <script>         function fetchJSONData() {             fetch('./sample.json')                 .then(response => {                     if (!response.ok) {                         throw new Error(`HTTP error! Status: ${response.status}`);                     }                     return response.json();                   })                 .then(data => console.log(data))                   .catch(error => console.error('Failed to fetch data:', error));          }         fetchJSONData();       </script> </body> </html> 
JavaScript
//sample.json {     "users": [       {         "site": "GeeksForGeeks",         "user": "Shobhit"       }     ]   }    

Output

Screenshot-2025-01-14-092110
Using the fetch() API to Read JSON Files

2. Using require() Method in Node.js

In a Node.js environment, require() is a simple way to read JSON files synchronously.

Syntax

const data = require('./sample.json');
console.log(data);
  • Create the JSON file (sample.json).
  • Use require() to import the JSON data.
  • Log or manipulate the data.
JavaScript
// Node.js example const data = require('./sample.json'); console.log(data); 
JavaScript
//sample.json {     "users": [       {         "site": "GeeksForGeeks",         "user": "Shobhit"       }     ]   }    
Screenshot-2025-01-14-094201
Using require() Method in Node.js

3. Using the import Statement for ES Modules

In modern JavaScript (ES Modules), use import ... assert { type: 'json' } to load JSON asynchronously in Node.js (v17+) and supported browsers.

Syntax

import jsonData from './path/to/jsonFile.json' assert { type: 'json' };
console.log(jsonData);
  • Enable ES Modules with .mjs or type: "module" in package.json.
  • Use import ... assert { type: 'json' } and process the data.
HTML
<html> <head></head> <body>     <h1>JSON Import Example</h1>     <p>Check your console for fetched data.</p>     <script type="module">         import jsonData from './sample.json' assert { type: 'json' };         console.log(jsonData);     </script> </body> </html> 
JavaScript
//sample.json {     "name": "Johina",     "age": 30,     "profession": "Developer" } 

Output

{
"name": "Johina",
"age": 30,
"profession": "Developer"
}
  • Browser compatibility :ES Modules with the import syntax are supported in modern browsers.
  • Node.js compatibility :Requires Node.js v17 or higher with appropriate module settings.
Screenshot-2025-01-14-102127
Using the import Statement for ES Modules

Next Article
Read JSON File Using JavaScript

S

shobhit_sharma
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Node.js
  • JSON
  • JavaScript-Methods
  • JavaScript-Questions

Similar Reads

    How to read a local text file using JavaScript?
    JavaScript can read local files using the File API, which is supported by most modern browsers. The File API allows JavaScript to read the contents of files chosen by the user, typically through an HTML file input element.The File object represents a file (like a text file or image) selected by the
    6 min read
    Convert XML to JSON using JavaScript
    Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency. Below are the approaches to convert XML
    2 min read
    JavaScript Program to read text File
    Given a text file, write a JavaScript program to extract the contents of that file. There is a built-in Module or in-built library in NodeJs that handles all the reading operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for reading operations is writte
    2 min read
    How to Parse JSON in JavaScript ?
    Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
    2 min read
    JavaScript JSON Objects
    JSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.const jsonData = { "key1" : "value1", ...
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences