Kuzt2114
Kuzt2114

Reputation: 25

Pulling a value from JSON

So I need to pull a value from a 3rd party website with node.js. Data is in JSON format. My code works for other similar causes but not for this one. I need to pull the price out of the according item. Data is structured in this way:

 {
"Glock-18 | Weasel (Battle-Scarred)": 0.52,
"PP-Bizon | Photic Zone (Minimal Wear)": 0.18,
"SSG 08 | Ghost Crusader (Field-Tested)": 0.62,
"Spectrum Case Key": 2.63,
"Sticker | shroud (Foil) | Krakow 2017": 5.62,
"Sticker | North | London 2018": 0.2,
"XM1014 | Slipstream (Field-Tested)": 0.08
}

My current code goes like this:

var Request = require("request");
var name ="Sticker | shroud (Foil) | Krakow 2017";

Request.get("url", (error, response, body) => {
    if(error) {
        return console.dir(error);
    }

    var object = JSON.parse(body);
    var price = object.name;
    console.log("price", price);
});

Any ideas why my price is always output as undefined?

Upvotes: 0

Views: 42

Answers (1)

O. Jones
O. Jones

Reputation: 108641

You shoud attempt to use var price = object[name]; because you want to use name as a variable. object.name does not do that.

You can always troubleshoot with console.log(object); to convince yourself you fetched the right stuff.

For best results, consider doing error checking this way. (Never trust web sites, eh?)

var object;
try {
    object = JSON.parse(body);
catch (e) {
   return console.dir('body not parseable', body, e);
}
if (!object) return console.dir('no object retrieved');
if (!object.hasOwnProperty(name)) return console.dir ('property not found', name);
var price = object[name];
console.log("price", price);

Upvotes: 2

Related Questions