Home > Back-end >  JSON data into variable
JSON data into variable

Time:05-21

EDIT: I solved that error, however, it only seems to print out just one instance. How can I make it put all the entries into that variable?

I'm a little bit too new to this, but I'm trying. Sorry if the question sounds stupid. I've configured a JSON server and it works just fine. I can pull out the data successfully, however, the data I receive I'd like to go into a variable so that I can use it later on in another function. For this purpose, I created the variable dategraph. However, it doesn't seem to work good. It doesn't seem to read it outside the $each loop. Any ideas what could it be? I tried using console.log() in the $each loop and it works fine, however, it won't work outside of it.

function solicitare() {
  adresa = "http://localhost:4000/listaexamene?callback=?";
  $.getJSON(adresa, function (raspuns) {
    $.each(raspuns, function (indice, examen) {
      continutDeAfisat = "<div><i>Subiect: "   examen.examId   "</i>, Student: "   examen.studentId   "</div>";
      $(continutDeAfisat).appendTo("#datenoi");

      var dategraph = {};
      dategraph.examId = examen.examId;
      dategraph.studentId = examen.studentId;
    });
    console.log(dategraph);
    stringNou = JSON.stringify(dategraph);
    console.log(stringNou);
  });
}

The error I receive is the following:

enter image description here

CodePudding user response:

You're declaring the variable in an inner scope. So the outer scopes don't know what that variable is. Try:

function solicitare() {
  let dategraph = {}; // <---
  const adresa = "http://localhost:4000/listaexamene?callback=?";
  $.getJSON(adresa, function (raspuns) {
    $.each(raspuns, function (indice, examen) {
      const continutDeAfisat = "<div><i>Subiect: "   examen.examId   "</i>, Student: "   examen.studentId   "</div>";
      $(continutDeAfisat).appendTo("#datenoi");

      dategraph.examId = examen.examId;
      dategraph.studentId = examen.studentId;
    });
    console.log(dategraph);
    const stringNou = JSON.stringify(dategraph);
    console.log(stringNou);
  });
}

Avoid using var and use let instead.

Simply doing myNewVariable = {}; will work, but javascript will not be very happy with you. When declaring new variables always use let or const.

Use const when you wont re-assign a value to a variable.

Use let when you will re-assign a value to a variable in the future.


Local Arrow Functions. Instead of doing:

$.getJSON(adresa, function (raspuns) {
  $.each(raspuns, function (indice, examen) {

You can do:

$.getJSON(adresa, (raspuns) => {
  $.each(raspuns, (indice, examen) => {

The only time you generally don't want to do this, is when you are working with the this keyword in javascript.


Unused local variables i.e. indice in your case, since you aren't using it. People usually do _ to indicate that it's an unused variable. So you can use either do _indice or _.


String interpolation. As you can see, its pretty annoying to do "<div><i>Subject:" examen.examId "....". Instead of "" make the string with ``. Then you can do string interpolation with variables like this ${examen.examId}.


This is what I'd do.

function solicitare() {
  const dategraph = {};
  const adresa = "http://localhost:4000/listaexamene?callback=?";
  $.getJSON(adresa, (raspuns) => {
    $.each(raspuns, (_, examen) => {
      const continutDeAfisat = `<div><i>Subiect: ${examen.examId}</i>, Student: ${examen.studentId}</div>`;
      $(continutDeAfisat).appendTo("#datenoi");

      dategraph.examId = examen.examId;
      dategraph.studentId = examen.studentId;
    });
    console.log(dategraph);
    const stringNou = JSON.stringify(dategraph);
    console.log(stringNou);
  });
}

If you write your javascript in VS code, I can also recommend to install an extension called prettier which will help format your code and make it more readable.


New question: How can I make it that it saves all the answers from the loop and not just one?

Try this:

First, make dategraph an array. Then we push each result object into the array. So something like this:

function solicitare() {
  const dategraph = []; // <--- make array
  const adresa = "http://localhost:4000/listaexamene?callback=?";
  $.getJSON(adresa, (raspuns) => {
    $.each(raspuns, (_, examen) => {
      const continutDeAfisat = `<div><i>Subiect: ${examen.examId}</i>, Student: ${examen.studentId}</div>`;
      $(continutDeAfisat).appendTo("#datenoi");
      
      // push result into array
      dategraph.push({
        examId: examen.examId,
        studentId: examen.studentId,
      });
    });
    console.log(dategraph);
    const stringNou = JSON.stringify(dategraph);
    console.log(stringNou);
  });

  console.log("Final dategraph:", JSON.stringify(dategraph, null, 2));
}
  • Related