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: main.js
This file demonstrates importing and using the JSON data.
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: main.js
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.
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