JavaScript: Extracting information from a JSON document

I'm attempting to retrieve data from a JSON file in a separate JavaScript file. The goal is to log the title from config.json using main.js.

Exploring the dynamic between JSON and JavaScript in this project has been my current focus. I have experimented with import and export methods, but encountered an "unexpected identifier" error. Extensive research has been done on this topic.

JSON Content:

{
    "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);

The desired outcome is for the console to display the title (which is currently set as "pretty cool title"). However, the actual result is an "unexpected identifier" message.

Answer №1

One way to retrieve JSON data is through the use of the fetch method.

// This function fetches and returns JSON data from a specified file path asynchronously
function getJSONData(path) {
    return fetch(path).then(response => response.json());
}

// Example of how to use the function to load JSON data and perform actions on it
getJSONData('data.json').then(data => {
    // Extract the 'name' property from the JSON object and display it in the console
    var name = data.name;
    console.log(name);  
}

UPDATE: If you prefer a more concise syntax, here's an alternative approach using async and await.

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

fetchData('data.json', info => console.log(info.name));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with object property not being recognized in Vue script, despite working fine in template

Currently, I am engaged in an exciting project using Vue. Within my Firestore database, I have a document named "default" within the collection "impostazioni" structured like this: impostazioni/default = { iniziata: false, finita: false, password: ...

Encountering an issue accessing a property retrieved from a fetch request in TypeScript

I am currently dealing with the property success defined in the API (reCAPTCHA). /** * The structure of response from the veirfy API is * { * "success": true|false, * "challenge_ts": timestamp, // timestamp of the challen ...

Trapped by commitments

I am currently working with an array of projects and an array of dates. My goal is to map the dates to the projects and make API calls to retrieve report URLs. I am trying to collect an array of objects that contain the URLs and the corresponding name-date ...

Using keyvalue pipe in Angular to iterate over objects through inserted loops

My Customized Answer import { Question } from './question'; export class Answer { AnswerId: number; Content: string; IsCorrect: boolean; Mark: number; QuestionId: number; Question: Question; } My Personal TestStartComp ...

How do webpack imports behave within a ReactJS project?

In my ReactJS project, I have utilized various 3rd party libraries such as lodash, d3, and more. Interestingly, I recently discovered that I did not explicitly write imports like import d3 from 'd3' or import _ from 'lodash' in all of ...

Obtaining entry to an ArrayList instance

Currently, I'm working on an application that processes JSON data to generate statistics. However, I've encountered a roadblock in my progress. The JSON data structure I'm dealing with looks like this: { "position":[ { "someKey1":"s ...

The small device screen in Bootstrap 4.5 is experiencing an issue where two rows are overlapping

I recently started learning Bootstrap and encountered an issue. When resizing the browser screen to a smaller size, I noticed that the rows within separate containers were overlapping. Screenshots have been provided for reference. Can someone please guide ...

Steps to exclusively close a textbox using the cancel button in HTML, BootStrap, and AngularJS

In my table, there is a column with an EDIT button at the bottom. When you click on EDIT, the column becomes editable and two buttons (SAVE and CANCEL) appear. If you click on CANCEL, I want the column to revert back to its non-editable state. Here is the ...

Tips for formatting numbers within a chart

One issue in my chart is that the values are not formatted correctly. For instance, I have a number 15900 and I would like it to be displayed as 15 900 with a space between thousands and hundreds. Below is the code snippet I would like to implement for s ...

Creating nested JSON structures from a JSON string can be achieved using various programming techniques

I'm attempting to create a nested JSON string, here is the JSON string I have: [ { 'CompanyID':'1', 'Name':'Company1', 'DepartmentName':'Executive General and Administrat ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

Utilized Python Selenium to interact with an element containing an x-click attribute, yet it failed to redirect

I'm currently attempting to scrape the following URL using Python's Selenium module. Link: https://www.rtilinks.com/?5b5483ba2d=OUhWbXlXOGY4cEE0VEtsK1pWSU5CdEJob0hiR0xFNjN2M252ZXlOWnp0RC9yaFpvN3ZNeW9SazlONWJSTWpvNGNpR0FwWUZwQWduaXdFY202bkcrUHAyb ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

Execute a PHP function using JavaScript/jQuery with AJAX requests

Hello everyone, I am reaching out for assistance with AJAX as I am still quite new to it. Despite the abundance of examples available, I find it challenging to grasp the concept. Specifically, I need help with my validation of a contact form using JavaScri ...

MongoDB function failing to properly return an array

I am currently exploring an efficient method to determine if each string within an array exists on MongoDB. The specific field to be queried is the 'name' field. However, I am encountering an issue when using the function below as it returns und ...

Creating a custom name for a specific node_module

Previously, we had a folder containing various typescript modules. However, we have now transformed that folder into a package. An issue arises with the existing code, as it uses webpack aliases for that particular folder. I am attempting to have those al ...

AngularJS - Setting an initial delay for ng-bind

We have a span element with the following attributes: <span role="link" ng-show="showLink()" ng-bind="textLink"></span> (Just an fyi: we implemented a fade-in, fade-out animation for this link, hence the use of ng-show instead of ng-if) The ...

Facing difficulty in converting JSON to Dictionary format

I am encountering an issue with JSON serialization into a class that has a dictionary property. The process involves converting a YAML file into JSON using libraries like YamlDotNet and NewtonSoft. You can find more information on this process here. Bel ...

What is the best way to customize Node.js configuration when it is executed through npm?

Check out this documentation on node config: node myapp.js --NODE_CONFIG='{"Customer":{"dbConfig":{"host":"customerdb.prod"}}}' However, if I run a npm script, all parameters will be passed to npm instead of nodejs, right? How can I pass the -- ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...