Import JSON Data in JavaScript Modules
Importing JSON Data:
Write a JavaScript program to import a JSON file as a module and access its properties.
Solution-1: Using import for JSON Files
Code:
File: data.json
This file contains JSON data.
//File: data.json
//This file contains JSON data.
{
"name": "Monika Nelinho",
"age": 30,
"profession": "Developer"
}
File: main.js
This file demonstrates importing and using the JSON data.
//File: main.js
//This file demonstrates importing and using the JSON data.
// Importing JSON data
import data from './data.json';
// Accessing properties from the JSON data
console.log('Name: ${data.name}'); // Logs "Name: John Doe"
console.log('Age: ${data.age}'); // Logs "Age: 30"
console.log('Profession: ${data.profession}'); // Logs "Profession: Developer"
Output:
Name: Monika Nelinho Age: 30 Profession: Developer
Explanation:
- data.json contains structured JSON data.
- main.js imports the JSON data as a module using import.
- The properties of the imported JSON object (name, age, and profession) are accessed and logged.
Solution-2: Using require for JSON Files (CommonJS)
Code:
File: data.json
//File: data.json
//This file contains JSON data.
{
"name": "Monika Nelinho",
"age": 30,
"profession": "Developer"
}
File: main.js
//File: main.js
//This file demonstrates importing JSON data using require.
// Importing JSON data using require
const data = require('./data.json');
// Accessing properties from the JSON data
console.log('Name: ${data.name}'); // Logs "Name: John Doe"
console.log('Age: ${data.age}'); // Logs "Age: 30"
console.log('Profession: ${data.profession}'); // Logs "Profession: Developer"
Output:
Name: Monika Nelinho Age: 30 Profession: Developer
Explanation:
- data.json contains structured JSON data.
- main.js imports the JSON data using require (CommonJS syntax).
- The properties of the imported JSON object are accessed and logged.
Improve this sample solution and post your code through Disqus
Previous: Mastering Aggregated Exports in JavaScript Modules.
Next: Exporting and Extending Classes in JavaScript.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics