What are the steps for importing and utilizing data from a JSON object?

After successfully importing data from a JSON file that was an Array, I've encountered a new challenge - my variable is now an object. My goal is to push all the questions from the object into an array and then display them on the HTML document. You can find the link to the JSON file in the code below.

Here is the JS code:


const myjson = 'http://tnij.xyz/bj5'; // LINK TO JSON FILE!
const questions = [];
fetch(myjson)
    .then(blob => blob.json('questions'))
    .then(data => questions.push(data))

console.log(questions);

Answer №1

(DISCLAIMER: I faced difficulties running the code due to cross-origin restrictions)

To address your issue, you have the option to either concatenate the incoming values using `.concat` or utilize `.apply`. In my opinion, opting for `.concat` would be preferable:

const myjson = 'http://tnij.xyz/bj5'; // URL TO JSON RESOURCE!
const inquiries = [];
fetch(myjson)
    .then(response => response.json())
    .then(data => {
        inquiries = inquiries.concat(data);
        console.log(inquiries);
    });

Keep in mind that the `inquiries` array will be empty outside of the `fetch` operation.

Answer №2

Here are a few things to note:

  • Instead of pushing the object retrieved from into an array, you can directly access the questions array by using jsonObj.questions. The entire JSON object received in response is referred to as jsonObj.
  • To display questions and answers in the HTML, you can follow this method:

var questions = [
    {
      "id": 1,
      "question": "Obwód trójkąta ABC wynosi 20cm. Jaką długość ma podstawa AB?",
      "answers": [
        {
          "id": 1,
          "answer": "8.4 cm",
          "correct": true
        },
        
        {
          "id": 2,
          "answer": "5.8 cm",
          "correct": false
        },
        
        {
          "id": 1,
          "answer": "0.6 cm",
          "correct": false
        },
        
        {
          "id": 1,
          "answer": "1.2 cm",
          "correct": false
        }
      ]
    }];
    
for(var i in questions) {
  document.getElementById('questions').innerHTML = questions[i].question;
  var answers = document.getElementById("answers");
  for(var j in questions[i].answers) {
    var label = document.createElement("label");
    var radio = document.createElement("input");
    radio.type = "radio";
    radio.name = "choices";
    radio.value = questions[i].answers[j].correct;
    label.appendChild(radio);
    label.appendChild(document.createTextNode(questions[i].answers[j].answer));
    answers.appendChild(label);
  }
}
<div id="questions">
</div>
<div id="answers"></div>

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

Accessing elements within a gridview

My gridview is connected to an objectdatasource and contains a bound textbox for input in each row. Next to the textbox, there is a button that triggers a javascript popup for unit conversion. I am wondering: how can I specify to the unit converter (Ja ...

Having trouble locating the CSS and JavaScript files within my Spring Maven project

I have a Spring framework application with a Maven project. In addition, I have CSS and JavaScript files under the WEB-INF folder. When attempting to link the JavaScript and CSS files like this: <link rel="stylesheet" href="../allDesign/js/vendor/anims ...

Adding elements to an array within a JSON object in Angular: What you need to know

Within my json object named "flowComponents," there is a string called "name" and an array of strings labeled "edition." As an example: { "_id": "553e87f3205465e83b46999b", "name": "FLOWCOMPONENT_CONTACTCOMBINATION_EDITION", "__v": 0, "edition ...

Storing the model on the server with the help of Backbone and NodeJS

As a beginner in Backbone and AJAX, as well as being new to Node.js which my server is built on, I am working on saving a model using the Save method in Backbone for a webchat project for university. Right now, my goal is to send the username and password ...

The href link does not direct to the main landing page

Clicking on the 'Visit website' button does not redirect me to home.html. Instead, it does nothing. How can I fix this issue? Any help would be appreciated. Preview.prototype = { create : function() { // Creating the Preview structur ...

Is it possible to change the name of a PHP file using the value entered in an input

I am currently in the process of trying to change the name of a file while uploading it using the JQuery uploader. I have made some progress, and here is the crucial part of my UploadHandler.php: protected function handle_file_upload($uploaded_file, $name ...

A guide to effortlessly converting Any[] to CustomType for seamless IntelliSense access to Properties within Angular/Typescript

Our Angular service interacts with the backend to retrieve data and display it on the UI. export interface UserDataResponse { id: number; userName: string; } AngularService_Method1() { return this.http.get<UserDataResponse[]>(this.appUrl + "/Ap ...

Having trouble linking a sqlite file in your tauri + vue project?

After successfully installing tauri-plugin-sql by adding the specified content to src-tauri/Cargo.toml : [dependencies.tauri-plugin-sql] git = "https://github.com/tauri-apps/plugins-workspace" branch = "v1" features = ["sqlite" ...

Storing a field of JSON object in Solr

I am a beginner with Solr and I am looking to index a JSON object that contains a field which is another JSON object. When I try to use the schema-less mode, I encounter this error: { "name": "BURGER KING", "phone": "+(1)-(403)-2153451", "ca ...

Tips on effectively extracting data from a SQLite JSON field that contains an array value

Within my sqlite database, there is a field that contains a complete JSON object. I need to perform some select queries on this JSON data. Specifically, I am looking to extract comments where the "pod" field is 'fb'. How can I properly extract th ...

Ways to efficiently populate HTML elements with JSON data

I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi a ...

Replacing field names in JSON using Lumen PHP

I have a database table with the following fields: id name xx Whenever I make an API call, I retrieve an item from the database and return it like this: $table = MyTable::select('table.*')->where('id', $id)->first(); return resp ...

Issue: Adjustment of elements' size using an "onclick" method when reaching specific screen width

Seeking assistance with implementing media queries in JavaScript. Can an object be resized from JavaScript code based on a specific screen width, rather than the default one? For example, if I have a button that opens a div with a height of 600px when cli ...

What is the best way to add a component into a MAP of other components in a React application?

I have a project where I am implementing a MAP function to iterate through an array of objects and present the data using a special Card component. However, I want to include another component called Banner after every second Card element from the loop, an ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Decrease the dimensions of the image while maintaining its width at 100%

I've got a dilemma with the images on my website that are linked from image hosting sites. They all need to be displayed at 100% width, but some of them have huge pixel dimensions which cause slow loading times. Is there a way to resize the images wi ...

React Traffic Light Component: Colors Stuck After Timeout

I've been working on solving a React issue and followed a tutorial on YouTube. I'm using CodeSandbox for my project, but I'm facing a problem where the colors of the signal are not showing up and do not change after some time. I even tried u ...

Unexpected Error: Unable to access the 'position' property of an undefined element (D3.JS)

This error occurred when I attempted to fetch JSON data and convert it into a line graph. An unexpected TypeError was thrown: Unable to access the 'position' property of undefined Below is the relevant portion of the JS code: d3.json("../js/ ...

Determine all subarrays within two integer arrays whose sum matches a specified target number

Given two integer arrays, find all subarrays whose sum equals a specified target number. For example, if array1 = [1,2,3,4] and array2 = [7,3,4], with the sumToFind being 5, the function findSubArrays(array1, array2, num) should output [[1,4],[2,3]]. I in ...

How can I transfer Gmail message using express rendering parameters?

Using passport-google-oauth for authentication and the node-gmail-api for fetching gmail, I aim to display gmail message after authentication. In order to achieve this, I have written the following code in routes.js: app.get('/profile', isLogged ...