1

I'm trying to get data from a JSON file from a different javascript file. I want to console log the title from config.json via main.js.

I am trying to learn about JSON and javascript and how they interact with this project. I have already tried using import and export, it tells me that is an unexpected identifier. I have tried researching it lots.

JSON Code:

{
    "Info": {
    "title": "Pretty Cool Title",
    "bio": "Pretty cool bio too in my opinion."
    }
}

Javascript Code:

import Info from "config.json";

var info = Info

var title = info.title

console.log(title);

My expected outcome is that the title (which I set to "pretty cool title") will be logged in the console. My actual result however is "unexpected identifier"

1 Answers1

1

By using fetch.

// return json data from any file path (asynchronous)
function getJSON(path) {
    return fetch(path).then(response => response.json());
}

// load json data; then proceed
getJSON('config.json').then(info => {
    // get title property and log it to the console
    var title = info.title;
    console.log(title);  
}

EDIT: Here is how to do it using async and await.

async function getJSON(path, callback) {
    return callback(await fetch(path).then(r => r.json()));
}

getJSON('config.json', info => console.log(info.title));
Mystical
  • 2,505
  • 2
  • 24
  • 43