Transforming a JSON information into a variable

9

I'm 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, that is, I want to use this way:

var buy = "o que vim no json no caso 2263.0";
    
asked by anonymous 12.01.2017 / 14:51

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 it would become an object, for 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;

So you can handle it to your liking.

    
12.01.2017 / 14:57
10

Complementing existing responses, if you have a string and not an object, you can convert it to 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 at CODEPEN .

    
12.01.2017 / 15:10
6

Use . to access the value of the object key:

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);
    
12.01.2017 / 14:54
5

Use this way:

var buy = json.buy;

You can use brackets too:

var buy = json['buy'];

Where json is the variable that contains your json.

    
12.01.2017 / 14:54
5

link

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);
    
12.01.2017 / 14:55