Search code examples
javascriptjsonconcatenation

JS - How to convert two strings and pass as one JSON object (NOT JSON.parse())


I just started learning about how to make http requests and APIs.

I've been using Bitcoinaverage API, which returns a JSON for the crypto and fiat currency that you request. The very first key in the json is an object that has it's name derived from the request you've made.

As an example, if you want the price of BTC in USD, the object's name will be BTCUSD. Or BTCEUR etc...

{
  BTCUSD: {   //The only key that changes based on your request. LTCUSD, ETHEUR etc...
    ask: 7825.19,
    bid: 7817.5,
    last: 7816.09,
    high: 8166.22,
    low: 7783.28,
    volume: 57342.21168518,
    open: {
      hour: 7844.91,
      day: 7900.31,
      week: 8769.23,
      month: 9812.03,
      month_3: 7226.94,
      month_6: 10081.48,
      year: 3883.6
    },
    averages: { day: 7948.24, week: 8573.39, month: 9315.18 },
    changes: { price: [Object], percent: [Object] },
    volume_percent: 71.59,
    timestamp: 1583923337,
    display_timestamp: '2020-03-11 10:42:17',
    display_symbol: 'BTC-USD'
  }
}

If I wanted to log, say the value of "last", I could write something like this:

app.post("/", function (req, res) {
    var crypto = req.body.crypto;
    var fiat = req.body.fiat;

    restClient.tickerAllGlobal(crypto, fiat, function(response) {
        var data = JSON.parse(response);
        console.log(data.BTCUSD.last);
    });
});

The above snippet obviously won't work if the user requested the price in Euros instead of USD. I thought I could just simply concatenate the two variables and write console.log(data.crypto+fiat.last); but I just get a "NaN" response. I'm guessing that's because crypto and fiat variables are strings when returned by body-parser.

I thought about using JSON.parse() but that won't work either since crypto+fiat is not valid json. Then I thought about using eval(), not sure if it would work but even if it did, it's not a good idea to use it on user input, right?

So how can I do this with the requests that I get from the user without repeating myself?

Here's the full code if something is unclear:

const express = require("express");
const bodyParser = require("body-parser");
const bitcoinAverage = require("bitcoinaverage");

const publicKey = '123456789...';
var restClient = bitcoinAverage.restfulClient(publicKey);

const app = express();
app.use(bodyParser.urlencoded({
    extended: true
}));


app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

app.post("/", function (req, res) {
    var crypto = req.body.crypto;
    var fiat = req.body.fiat;

    restClient.tickerAllGlobal(crypto, fiat, function(response) {
        var data = JSON.parse(response);
        var price = data.crypto+fiat.last;

        console.log(price);
    });
});


app.listen(3000, function () {
    console.log("Server running:3000");
});


Solution

  • You can access dynamically created JSON keys using the syntax data["YOUR STRING HERE"]

    So in your example, something like data[crypto+fiat]