Unable to retrieve information from compact JSON files

It's been 2 hours and I still can't figure this out

I need help with reading my Json Data in my JavaScript File, saving it to a variable, and then printing it out.

I've tried multiple solutions but nothing seems to work (I'm new to JS). Can someone please assist:

This is what my Json File looks like:

var Quotes = {
    "allQuotes": [{
        "person": "- Martin Luther King Jr.",
        "quote": "In the End, we will remember not the words of our enemies, but the silence of our friends."

    }, {
        "person": " Uknown",
        "quote": "I am big! It is the pictures that got small."

    }, {
        "person": "- Apocalypse Now",
        "quote": " love the smell of napalm in the morning."

    }, {
        "person": " - Gone With the Wind",
        "quote": "Frankly, my dear, I do not give a damn."

    }, {
        "person": "- - Knute Rockne All American",
        "quote": " Tell em to go out there with all they got and win just one for the Gipper."

    }, {
        "person": "- Walt Disney",
        "quote": " It is kind of fun to do the impossible."

    }]
}

I'm using CodePen, here is the link: http://codepen.io/pat_the_hat_1992/pen/qqWmYL

//Please take a look at my code and make any necessary edits

Answer №1

Your content does not adhere to proper JSON formatting. Remember, JSON is a data format and cannot contain JavaScript variables or assignments within its structure.

{
"allQuotes": [{
    "person": "- Martin Luther King Jr.",
    "quote": "In the End, we will remember not the words of our enemies, but the silence of our friends."
}, {
    "person": " Uknown",
    "quote": "I am big! It is the pictures that got small."
}, {
    "person": "- Apocalypse Now",
    "quote": " love the smell of napalm in the morning."
}, {
    "person": " - Gone With the Wind",
    "quote": "Frankly, my dear, I do not give a damn."
}, {
    "person": "- - Knute Rockne All American",
    "quote": " Tell em to go out there with all they got and win just one for the Gipper."
}, {
    "person": "- Walt Disney",
    "quote": " It is kind of fun to do the impossible."
}]
}

Removing var Quotes = will rectify your JSON file.

To fetch a JSON file in JavaScript, consider using XMLHttpRequest or $.ajax with jQuery.

Example with Vanilla Javascript

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/myJsonFile.json');
xhr.onload = function() {
    var quotes = JSON.parse(xhr.responseText);
    console.log(quotes);
};
xhr.send();

Alternatively, you can use jQuery:

jQuery Example

$.ajax({
    method: "GET",
    url: "http://localhost/myJsonFile.json",
    dataType: "json",
    success: function(json) {
        console.log(json);
    }
  });

Note that using $.ajax or XMLHttpRequest necessitates hosting your file on a web server. Accessing it from a local filesystem will not work.

For Further Exploration

Explore more about XMLHttpRequest here.

Learn more about JSON at this link.

For insights on Jquery's $.ajax, visit this page.

Answer №2

Check out the following code snippet which demonstrates how I achieve this:

let data = JSON.parse(Quotes);
for (let i = 0; i < data.allQuotes.length; i++) {
    let quoteObj = data.allQuotes[i];
    alert(quoteObj.person + " says " + quoteObj.quote);
}

Answer №3

Did you attempt the method demonstrated on the official W3C website? It involves using '+' to concatenate the JSON text:

    var jsonData = '{ "employees" : [' +
    '{ "firstName":"John" , "lastName":"Doe" },' +
    '{ "firstName":"Anna" , "lastName":"Smith" },' +
    '{ "firstName":"Peter" , "lastName":"Jones" } ]}';

And then converting the JSON into a JavaScript Object, so that JavaScript can interpret it:

    var obj = JSON.parse(jsonData);

To utilize the object in your code, you would do something like this:

    document.getElementById("id").innerHTML =
    obj.employees[1].firstName + " " + obj.employees[1].lastName;

In this scenario, it would display "John Doe" because obj.employees[0].firstName is "John" and obj.employees[0].lastName is "Doe"

If you prefer using JQuery to display the data:

    $("id").append(obj.employees[0].firstName + " " + obj.employees[0].lastName);

or

    $("id").text(obj.employees[0].firstName + " " + obj.employees[0].lastName);

Below is a snippet demonstrating how to implement this on an actual webpage (it will show "Anna Smith" in the H1 Element):

<!DOCTYPE html>
<html>
    <body>
        <h1 id="demo"></h1>
        <script>
            var jsonData = '{ "employees" : [' +
            '{ "firstName":"John" , "lastName":"Doe" },' +
            '{ "firstName":"Anna" , "lastName":"Smith" },' +
            '{ "firstName":"Peter" , "lastName":"Jones" } ]}';

            var obj = JSON.parse(jsonData);

            document.getElementById("demo").innerHTML =
            obj.employees[1].firstName + " " + obj.employees[1].lastName;
        </script>
    </body>
</html>

Source: http://www.w3schools.com/js/js_json.asp

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

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...

Exports for Express Router Module/Functions

I am currently working on exporting a function and an express router from the same file. The function is intended to verify certificates, while the route is meant to be mounted on my main class for other routes to use. I want to encapsulate both functional ...

How can I create a custom Sweet Alert button in JavaScript that redirects to a specific webpage when clicked?

Here's what I have in my code: swal({ title: 'Successfully Registered!', text: "Would you like to proceed to the Log In page?", type: 'success', showCancelButton: true, confirmButtonColor: '#308 ...

Python 3 loop malfunctioning

Recently, I've been delving into Python and conducting some experiments. At home, I have a weather station connected to a JSON Web API. My goal is to use Python to display the temperature on a screen. However, I'm encountering an issue where the ...

What is the process for importing a class (.js file) into a .vue file?

I am facing an issue with my Vue application. I have created a class named `Authenticator` in the file `Authenticator.js`, and now I need to utilize its functions in my `Login.vue` file. Could someone guide me on how to properly export the `Authenticator` ...

Unable to activate click function in Jquery

Here is a basic HTML page snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script> <script> $(document).ready(function () { $('#test').click(); }); < ...

Is Angular 2+ responsible for loading the entire module or only the exported components within it?

I'm dealing with a situation where I have a large module but only need to export one specific component. I'm wondering if Angular loads the entire module or just the exported components, as I want to optimize performance without compromising the ...

What is the Vercel equivalent to .netlify/functions?

I'm in the process of deploying this repository: https://github.com/DataStax-Examples/astra-tik-tok using Vercel instead of Netlify. I've converted vanilla React to Next.js, but I'm unsure how to transition the code in the Home.js file to w ...

Vue - unable to display component CSS classes in application when using class-style bindings

Just diving into Vue and starting with class-style binding syntax. I'm facing an issue where the CSS classes for header and footer that I've defined are not displaying, even though I've referenced them in the component tags. Can't seem ...

Sort the array in alphabetical and numerical order while meeting a specific condition

In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10 comes after single digits and follows a specific order after that. Initially, I tried to prioritize strings containing the word first, but whe ...

My goal is to extract the usernames of all sellers from the Poshmark webpage using a combination of JavaScript, Cheerio, and Axios

After experimenting with various methods, I've come close to the solution, but it only retrieves one of the div elements I'm looking for... Although I managed to retrieve multiple divs at one point, when I attempted to extract text using the .te ...

Tips for passing parameters to an ajax request in Django URL?

In my current setup, I'm passing a URL to the ajax like this: $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://loc ...

Error occurred when trying to run 'npm run dev' on vite: Unable to access the file "node_modules/react/jsx-dev-runtime.js"

After successfully creating a Vite app, I encountered three errors when trying to run the app with npm run dev: [ERROR] Cannot read file "node_modules/react/jsx-dev-runtime.js": Access is denied. [ERROR] Cannot read file "node_modules/react/index.js": Acc ...

How can I showcase CSV data as clickable links and images on a website using HTML?

Looking for a way to display CSV file links as clickable hyperlinks in a table? Want to directly show images from photo links on your website as well? Wondering if this is even possible? Successfully showcased desired content in a table with the code prov ...

"Exploring the world of Python API integration and dictionary

I have been struggling to figure out how to only print the word "devices" in my code, despite trying multiple methods. Can anyone provide guidance on how to achieve this? Additionally, I would like to know how to print the "model" of a single device or b ...

Enhance the functionality of NodeJS core applications

I recently attempted to modify some custom functions in the FS module of NodeJS, which is an integral part of NodeJS' core modules. The specific file I targeted was fs.js, located in /usr/lib/nodejs. However, despite making changes to the code, I noti ...

What could be causing the "Failed to decode JSON object: No JSON object could be decoded" error to appear in my program?

Below is the code I have written: @url_api.route("/add") class AddIPvFour(Resource): """ This class contains functions to add a new URL. """ def post(self): """ Add a new URL map to an IP or update existing. :retu ...

Retrieving and storing information from a form without the need to submit it

I have been given the task of creating a load/save feature for a complex form. The goal is to allow users to save their progress and resume working on it at a later time. After much consideration, I have decided to implement server-side storage by saving ...

Is React Authentication with Ruby Gem Devise possible in JavaScript?

Recently, I started working on a rails app and decided to switch the front end to React gradually. Currently, my focus is on converting the menu bar with dynamic links based on whether the user is logged in or not. Below is the original code snippet from t ...