Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Export a JSON database to use in JavaScript

I just barely started learning JavaScript by myself and have a question to ask.

I have a JSON database I created, and a JavaScript file connecting to this same db, on another js file I have a function that I call with a button, how can I get the data from my JSON database into the js file with the function?

Here’s how my code looks like right now

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index.html

<head><script src="script.js" type="text/javascript"></script><script src="db_connection.js" type="module"></script></head><body><button onclick="showData()">Show Data</button></body>

script.js

import { data } from "./db_connection.js"; function showData() {   console.log(data[0].name); }

db_connection.js

import data from "./database.json" assert { type: "json" }; export default { data };

database.json

[   { "id": 1, "name": "Jason", "year": 2020 },   { "id": 2, "name": "Freddy", "year": 2021 } ]

The console returns "Uncaught SyntaxError: Cannot use import statement outside a module" and "Uncaught ReferenceError: showData is not defined at HTMLButtonElement.onclick"

Can anyone help?

>Solution :

I add code below.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript JSON Example</title>
  <script src="script.js" type="module"></script>
  <script src="db_connection.js" type="module"></script>
</head>
<body>
  <button onclick="showData()">Show Data</button>
</body>
</html>

script.js:

// script.js
import { data } from "./db_connection.js";

export function showData() {
  console.log(data[0].name);
}

db_connection.js:

javascript
Copy code
// db_connection.js
import data from "./database.json";

export { data };

database.json:

[
  { "id": 1, "name": "Jason", "year": 2020 },
  { "id": 2, "name": "Freddy", "year": 2021 }
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading