w3resource

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.

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that imports a JSON file as a module and logs its properties to the console.
  • Write a JavaScript program that uses dynamic import() to load a JSON file and display its data on the webpage.
  • Write a JavaScript program that imports JSON data and then uses it to populate a table dynamically.
  • Write a JavaScript program that validates the structure of the imported JSON data before processing it.

Go to:


PREV : Aggregating Exports.
NEXT : Exporting Classes.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.