'How to get specific value from Json in node js

Im trying to get gas price using this website https://ethgasstation.info/api/ethgasAPI.json and getting this: {"fast":1000,"fastest":1220,"safeLow":830,"average":890,"block_time":15.305084745762711,"blockNum":14119898,"speed":0.2507512562294746,"safeLowWait":19,"avgWait":3.5,"fastWait":0.5,"fastestWait":0.5,"gasPriceRange":{"4":255.1,"6":255.1,"8":255.1,"10":255.1,"20":255.1,"30":255.1,"40":255.1,"50":255.1,"60":255.1,"70":255.1,"80":255.1,"90":255.1,"100":255.1,"110":255.1,"120":255.1,"130":255.1,"140":255.1,"150":255.1,"160":255.1,"170":255.1,"180":255.1,"190":255.1,"200":255.1,"220":255.1,"240":255.1,"260":255.1,"280":255.1,"300":255.1,"320":255.1,"340":255.1,"360":255.1,"380":255.1,"400":255.1,"420":255.1,"440":255.1,"460":255.1,"480":255.1,"500":255.1,"520":255.1,"540":255.1,"560":255.1,"580":255.1,"600":255.1,"620":255.1,"640":255.1,"660":255.1,"680":255.1,"700":255.1,"720":255.1,"740":255.1,"760":255.1,"780":255.1,"800":255.1,"820":25.3,"830":19,"840":11.4,"860":7.7,"880":4.1,"890":3.5,"900":2.9,"920":2.5,"940":1.8,"960":1.5,"980":0.8,"1000":0.5,"1020":0.5,"1040":0.5,"1060":0.5,"1080":0.5,"1100":0.5,"1120":0.5,"1140":0.5,"1160":0.5,"1180":0.5,"1200":0.5,"1220":0.5}}

and I want to get Average value, but how any suggestions?



Solution 1:[1]

To do this you will need to convert this string to a JSON object and then you will be able to access the average value, check out the exemple below:

// your string
const jsonString = '{"fast":1000,"fastest":1220,"safeLow":830,"average":890}';

// Convert it to JSON object
const gasObject = JSON.parse(jsonString);

// Read the average value
console.log(gasObject.average)

If you havent made the http request yet, this code snippet will help you:

const https = require("https");

https
  .get("https://ethgasstation.info/api/ethgasAPI.json", (resp) => {
    let data = "";
    // A chunk of data has been received.
    resp.on("data", (chunk) => {
      data += chunk;
    });

    resp.on("end", () => {
      // Read the average here
      console.log(JSON.parse(data).average);
    });
  })
  .on("error", (err) => {
    console.log("Error: ", err);
  });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank Wendel