How to get the value of a field of a JSON object

Asked

Viewed 949 times

1

How can I pick up the correspondent to earnings in JSON (Value 0€) and output in Javascript?

That is, so that on the website the corresponding to Earnings (0€) in what I identified as OUTPUT DE EARNINGS AQUI in Javascript.

JSON

{
  "DataInfo":[
    {
      "Earnings": "0€",
      "Orders": "0"
    }
  ]
}

JS

function Earnings() {
  var ElementEarnings = document.getElementById("Earnings");
  ElementEarnings.innerHTML = OUTPUT DE EARNINGS AQUI (0€);
}

WEBSITE

function Earnings() {
  var ElementEarnings = document.getElementById("Earnings");
  ElementEarnings.innerHTML = "OUTPUT DE EARNINGS AQUI (0€)";
}

function Orders() {
  var ElementOrders = document.getElementById("Orders")
  ElementOrders.innerHTML = "1";
}

function JSONLOAD() {
  "use stric";

  fetch("Static/Data/DATA.json")
    .then(function(resp) {
      return resp.json();
    })
    .then(function(data){
      var Earnings = data.Earnings;
      var Orders = data.Orders;
      console.log(data);
    })
}

Earnings()
Orders()
JSONLOAD()
body {
  margin-left: 0px;
  margin-right: 0px;
  margin-top: 0px;
  margin-bottom: 0px;
  background: #252C35;
  color: white;
}

#UpperBar {
  height: 45px;
}

.MASlime {
  position: absolute;
  font-size: 30px;
  top: 1px;
  left: 40px;
}

#Totals {
  position: absolute;
  font-size: 30px;
}

.Total {
  position: absolute;
  top: 70px;
  left: 130px;
}

.TotalEarnings {
  position: absolute;
  top: 70px;
  left: 200px;
}

.TotalO {
  position: absolute;
  top: 140px;
  left: 130px;
}

.TotalOrders {
  position: absolute;
  top: 140px;
  left: 200px;
}

#Earnings {
  position: absolute;
  top: 70px;
  left: 350px;
}

#Orders {
  position: absolute;
  top: 140px;
  left: 350px;
}

.NewOrder {
  position: absolute;
  top: 250px;
  left: 200px;
  font-size: 30px;
}

.OrderName {
  position: absolute;
  top: 350px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.OrderDate {
  position: absolute;
  top: 400px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.SKU {
  position: absolute;
  top: 450px;
  left: 140px;
  width: 250px;
  height: 25px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.SUBMIT {
  position: absolute;
  top: 500px;
  left: 220px;
  width: 100px;
  height: 40px;
  background-color: #252C35;
  color: white;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  border-color: white;
  padding: 5px;
}

.Menu {
  position: absolute;
  top: 25px;
  left: 480px;
  font-size: 30px;
  cursor: pointer;
}

.menu {
  text-align: center;
  width: 100%;
}

.menu a {
  display: block;
  border-bottom: 1px solid #EAEAED;
  border-top: 1px solid #EAEAED;
  text-decoration: none;
  color: white;
  margin-top: 120px;
  padding-bottom: 10px;
  padding-top: 10px;
  font-size: 30px;
  background: #252C35;
}

.All {
  display: block;
}

#toggle {
  display: none;
}

.fadeIn {
  animation: fadein 1.3s ease-in;
}

@keyframes fadein {
  0% { opacity: 0; }
  25% { opacity: 0.3; }
  50% { opacity: 0.5; }
  75% { opacity: 0.8; }
  100% { opacity: 1; }
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>EComerce App Slime</title>
    <link rel="stylesheet" href="Static/css/index.css">
  </head>
  <body>
    <div id="menu">
      <label for="toggle" class="Menu">&#9776;</label>
      <input type="checkbox" id="toggle" onclick="meuMenuToggle()"/>
      <div class="menu">
          <a href="#">Slime Recipe</a>
      </div>
    </div>
    <div id="UpperBar">
      <p class="MASlime">MASlime</p>
    </div>
      <div id="HomePage">
        <div id="Totals">
          <p class="Total">Total</p>
          <p class="TotalEarnings">Earnings</p>
          <p class="TotalO">Total</p>
          <p class="TotalOrders">Orders</p>
          <p id="Earnings">100€</p>
          <p id="Orders">1</p>
        </div>
        <div id="NewOrder">
          <p class="NewOrder">New Order</p>
          <form id="OrderForm">
            <input class="OrderName" type="text" name="OrderName" placeholder="Buyer Name" required>
            <input class="OrderDate" type="text" name="OrderDate" placeholder="Date of Order" required>
            <input class="SKU" type="text" name="ProductSKU" placeholder="Product SKU" required>
            <input class="SUBMIT" type="button" name="Submit" value="SUBMIT">
          </form>
        </div>
    </div>
    <script>
    var home = document.getElementById('HomePage');
    var menu = document.getElementsByClassName('menu')[0];
    menu.style.display = 'none';

    document.getElementById('toggle').onclick = () => {

    if (menu.style.display == 'none') setTimeout(fadeMenu, 150);
    else if(menu.style.display == 'block') setTimeout(fadeHome, 150);
  }

    function fadeMenu() {
      home.style.display = 'none';
      menu.classList.add('fadeIn');
      menu.style.display =  'block';
    }

    function fadeHome() {
      home.style.display = 'block';
      home.classList.add('fadeIn');
      menu.style.display = 'none';
    }
    </script>
    <script src="Static/js/index.js"></script>
  </body>
</html>

2 answers

1

You need to pass on the answer you got on fetch for the function that inserts the Earnings on the page.

function appendEarnings(earnings) {
  var ElementEarnings = document.getElementById("Earnings");
  ElementEarnings.innerHTML = earnings
}

function JSONLOAD() {
  "use stric";

  fetch("Static/Data/DATA.json")
    .then(function(resp) {
      return resp.json();
    })
    .then(function(data){
      var Earnings = data.DataInfo[0].Earnings;
      appendEarnings(Earnings)
    })
}
  • I put it this way : https://pastebin.com/g081zmAv But he is saying in the cosola this Uncaught SyntaxError: Unexpected token . index.js:18

  • @hkotsubo I put it this way : Pastebin.com/g081zmAv But he is saying in the cosola this Uncaught Syntaxerror: Unexpected token . index.js:18

  • @Deadsec I did not test, but in a quick look, missed the parameter in the first function: function appendOrders(orders), and further down is use strict ("t" was missing). But maybe there is another error in other parts of the code, because testing only with what you passed, I had no syntax error...

  • @hkotsubo All problems have been solved Thank you!

  • @Deadsec If one of the answers solved your problem, you can choose the one that best solved it and accept it, see here how and why to do it. It’s not mandatory, but it’s good site practice to indicate to future visitors that it solved the problem (but if you think none of them actually solved it, then you don’t have to accept any). Don’t forget that you can also vote in all the answers you found useful.

1

First we have to understand what the structure of a JSON. Using your case as an example:

{
  "DataInfo":[
    {
      "Earnings": "0€",
      "Orders": "0"
    }
  ]
}

The keys ({ and }) define an object, which is nothing more than a set of several key/value pairs. Each key/value pair is written in the format chave : valor, i.e., a string with the key name¹, followed by two dots, followed by the value.

So the object above has a key "DataInfo", whose value is:

[
  {
    "Earnings": "0€",
    "Orders": "0"
  }
]

The clasps ([ and ]) delimit an array, that is a list of one or more values. Therefore, the key value DataInfo is an array.

Within this array, we have:

{
  "Earnings": "0€",
  "Orders": "0"
}

I mean, it’s another object, which has two keys:

  • "Earnings", whose value is "0€"
  • "Orders", the value of which is "0"

So we have an object that holds the key "DataInfo", whose value is an array. Within this array we have only one element, which is another object, which has the keys "Earnings" and "Orders".

That is, to obtain the value of Earnings, just go through this structure. If your object is called data, to get the value of the key DataInfo, just do data.DataInfo, and this will be an array.

To get the first element of the array, do data.DataInfo[0] (since the first element of an array is element zero). And to get the value of the key Earnings of this object, make data.DataInfo[0].Earnings. And to take the value of Orders, the idea is the same: data.DataInfo[0].Orders.

let data = {
  "DataInfo":[
    {
      "Earnings": "0€",
      "Orders": "0"
    }
  ]
};

console.log(data.DataInfo[0].Earnings); // 0€
console.log(data.DataInfo[0].Orders); // 0

Then just do:

fetch("Static/Data/DATA.json")
  .then(function(resp) {
    return resp.json();
  })
  .then(function(data){
    document.getElementById("Earnings").innerHTML = data.DataInfo[0].Earnings;
  });

(1): In Javascript also can use numbers as a key, for they are automatically converted to strings.

  • 1

    Very well explained how it works!

  • If I use the first example (What vs uses Json inside js) I could later change the information inside the website?

  • @Deadsec I don’t know if I understand your doubt, but anyway, if you have access to DOM (via document) and has access to JSON data (either within the fetch, either at any other point in the code), you can manipulate the page elements (using the document) using JSON data. If applicable, you can open another question with the more specific question, so you increase the chances of being answered (because new questions are visible to everyone, while comments are only visible here) and the site becomes more organized (a question for doubt) :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.