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

Combining PHP JQuery Dialog with Datatables results in a sleek design loss

Recently, I encountered an issue with my code. I have a file called incident_view.php which pulls data from the database and displays it using Datatables. Everything was working fine until I tried to open this page in a JQuery dialog on another page called ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container: $('img').each(function(i){ var parent_width = parseInt($(this).parent().width()), image_width = parseInt($(this).width()); ...

Struggling with a TypeError in React/Next-js: Why is it saying "Cannot read properties of undefined" for 'id' when the object is clearly filled with data?

Encountering an issue with a checkbox list snippet in Next-js and React after moving it to the sandbox. Each time I click on a checkbox, I receive the error message: TypeError: Cannot read properties of undefined (reading 'id') This error is co ...

How can I preserve the line break in a textarea using PHP?

Is it possible to maintain line breaks in a textarea using PHP? Currently, I have a temporary solution that involves using the exec function to run a shell command, but I would prefer a purely PHP approach. Below is my temporary script - can you help me mo ...

Verify the MAC address as the user types

I need to verify a form field for MAC Addresses and have implemented the following code that does the job. $('body').on('keyup', '#macAddess', function(e){ var e = $(this).val(); var r = /([a-f0-9]{2})([a-f0-9]{2})/i, ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Convert the entirety of this function into jQuery

Can someone please help me convert this code to jQuery? I have a section of jQuery code, but I'm struggling with writing the rest! function showUser(str) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Implementing a delay between two div elements using jQuery

I have two Divs with the class "sliced", each containing three images with the class "tile". When I animate using jQuery, I am unable to add a delay between the "sliced" classes. However, I have successfully added a delay between the "tile" classes. index ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

The onchange() function for a multi-checkbox dropdown is failing to work as

Issue with Multiple Drop Down Checkbox Functionality: The first parameter is always received as undefined, and the onchange event only captures the value of the first checkbox selected. <select name="multicheckbox[]" multiple="multiple" class="4colacti ...

Traveler encountering Flask website displaying 500 error on Dreamhost platform

I'm struggling to configure Passenger with Flask on my DreamHost server. The Flask site is running inside a virtualenv with Python 3.5.2. The goal is to take input from a query string in the URL, parse a JSON file on the server, search for the given q ...

Having an issue with the pop state function not functioning correctly

I am facing an issue with my images where clicking on a specific image changes the URL to that ID. However, I can only go back once and then the same URL is repeated every time I press the back button. Additionally, the forward button does not work at all. ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...

Trying to dynamically filter table cells in real time using HTML and jQuery

During my search on Stack Overflow, I successfully implemented a real-time row filtering feature. However, I now require more specificity in my filtering process. Currently, the code I am using is as follows: HTML: <input type="text" id="search" place ...

What is the best way to dynamically update form fields in a database after making a selection in a <select> component?

Currently, I have a form that displays a list of stars (stellar objects) with a <select> control and two <inputs>. I am seeking guidance on how to populate the two inputs from the database when the user changes the selection in the <select&g ...

What causes the console.log function to behave in this manner?

When using the node.js interpreter, if you run the code: console.log("A newline character is written like \"\\ n \"."); //output will be:- // A newline character is written like "\ n ". However, if you just enter the following in ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...