Transforming a JSON information into a variable

Asked

Viewed 4,393 times

9

I am calling a function in Node.js and it returns a JSON:

{
  "pair": "BTCBRL",
  "last": 2280.0,
  "high": 2306.0,
  "low": 2205.0,
  "vol": 113.17267938,
  "vol_brl": 255658.20705113,
  "buy": 2263.0,
  "sell": 2279.77
}

I would like to use only the "buy" information of this json, ie, I want to use so:

var buy = "o que vim no json no caso 2263.0";
  • This Jon is returned in a variable, right? Then just use: var buy = "what I came to in json in the case "+ data.buy; where date is your json.

5 answers

10


I will try to write in a very didactic way, and not in a practical way.

Json is a string, but if you assign a variable the same becomes an object, example:

var informacoes = {
    "pair": "BTCBRL",
    "last": 2280.0,
    "high": 2306.0,
    "low": 2205.0,
    "vol": 113.17267938,
    "vol_brl": 255658.20705113,
    "buy": 2263.0,
    "sell": 2279.77
 }

then you can do something like:

var buy = informacoes.buy;

Then you can manipulate to your liking.

10

Complementing existing responses if you have a string and not an object, can convert with JSON.parse:

var str = '{ "pair": "BTCBRL",  "last": 2280.0, "high": 2306.0, "low": 2205.0, "vol": 113.17267938, "vol_brl": 255658.20705113, "buy": 2263.0, "sell": 2279.77 }';

var obj = JSON.parse(str);

See working on CODEPEN.

6

Utilize . to access the object’s key value:

var obj = {
  "pair": "BTCBRL",
  "last": 2280.0,
  "high": 2306.0,
  "low": 2205.0,
  "vol": 113.17267938,
  "vol_brl": 255658.20705113,
  "buy": 2263.0,
  "sell": 2279.77
}
var buy = "o que vim no json no caso " + obj.buy;
console.log(buy);

5

Use like this:

var buy = json.buy;

You can use brackets too:

var buy = json['buy'];

Where json is the variable that contains your json.

5

https://jsfiddle.net/0wL68po2/

var objeto = {
"pair": "BTCBRL",
"last": 2280.0,
"high": 2306.0,
"low": 2205.0,
"vol": 113.17267938,
"vol_brl": 255658.20705113,
"buy": 2263.0,
"sell": 2279.77
 }
alert(objeto.buy);

Browser other questions tagged

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