I have been trying to use an API from https://api.nomics.com/ and I cant seem to use the data inside the JSON object. I want to get the "price" value and display it in the console log but it keeps saying my variable is undefined please assist:
app.post("/", function(req, res) {
request("https://api.nomics.com/v1/currencies/ticker?key=demo-26240835858194712a4f8cc0dc635c7a&ids=BTC&interval=1d&convert=USD&per-page=10&page=1", function(error, response, body) {
var data = JSON.parse(body);
var price = data.price;
console.log(data);
console.log(price);});});
The result I get is:
[ {
"id": "BTC",
"currency": "BTC",
"symbol": "BTC",
"name": "Bitcoin",
"logo_url": "https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg",
"status": "active",
"price": "10609.61844458",
"price_date": "2020-10-07T00:00:00Z",
"price_timestamp": "2020-10-07T08:12:00Z",
"circulating_supply": "18510093",
"max_supply": "21000000",
"market_cap": "196385024104",
"num_exchanges": "361",
"num_pairs": "38888",
"first_candle": "2011-08-18T00:00:00Z",
"first_trade": "2011-08-18T00:00:00Z",
"first_order_book": "2017-01-06T00:00:00Z",
"rank": "1",
"rank_delta": "0",
"high": "19337.69352527",
"high_timestamp": "2017-12-16T00:00:00Z",
"1d": {
"volume": "16456552525.84",
"price_change": "-148.44596940",
"price_change_pct": "-0.0138",
"volume_change": "1509811120.10",
"volume_change_pct": "0.1010",
"market_cap_change": "-2739282102.40",
"market_cap_change_pct": "-0.0138"
} }]
var price is undefined. is it because of the "[]" that is surrounding the JSON object?
Yes it's because the request you are making return an array of objects, so you need to get the first element and on that get the price.
var price = data[0].price;
Related
I have below code which is going to invoke REST endpoint and return response back. I just tried to print the response.body in the console and It works perfectly fine.
var express = require('express');
var app = express();
var PORT = 8001;
var request = require('request');
var HashMap = require('hashmap');
var endPoint="http://sandbox.dev.amazon.com/idsearch/environment/amazon/";
app.get('/productId/:proId',async (req,res) => {
try
{
var headers ={
"accept":"application/json"
}
var options = {
url:endPoint.concat(req.params.proId),
headers:headers
}
request(options, (error,response,body)=> {
console.log(response.body) // It returned response as below output JSON file
res.send("STATUS CODE : 200");
});
}
catch(error)
{
throw error;
}
});
Output:
{
"<Some dynamic Content>": {
"type": "PROD-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
The above output contains all the responses with respective Endpoint URL which is expected. But I just want to fetch only the object contains "Status: 1". I'm just wondering that How can I manipulate the response.body object to get the below JSON as output.
Expected Output:
{
"callSummary":[
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
]
}
I just want to iterate the response.body obj and check the status as 1 if it's then I need to fetch all the details and form it as above payload. This is dynamic content but the template format is static.
I tried the below code to iterate the response.body but no luck.
var string = JSON.stringify(response.body);
var objectValue = JSON.parse(string);
var obj = objectValue.callSummary;
console.log(obj.length); // It returned undefined.
Please lead me to achieve this.
To return that json, just
res.json(response.body['<Some dynamic Content>'].callSummary);
Adding some validation and error handling would be a good idea before sending the response.
In case your key is just an example and you never know your first key value, and you always want the values of the first key
res.json(Object.values(response.body)[0].callSummary);
Object.values returns an array, so you can iterate the values if you want manage more than the first one
I'm writing tests in POSTMAN against a POST API request by sending JSON body data of the following format:
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"activities" : null
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe"
}
}
I get Response for the request in similar format with some added details:
{
"status": "Success",
"message": "Created new 'Student' record",
"correlationCode": "Z848640-261354",
"type": {
"id": 51247,
"name": "Student",
"slug": "student",
"application": {
"name": "Willow University"
}
},
"data": {
"name": "Amber Joseph",
"dob": "1988-10-13",
"addressLine1": "Ap #770-9459 Quis Av.",
"state": "WA",
"suburb": "Beverley",
"yesNo": false,
"balance": 423.00,
"club": [
"Dance",
"Sports"
],
"libraryCard": {
"uid": "2d07d77c-8756-43d4-912f-238a2ff567fe",
"name": "11206"
}
}
Now i want to achieve two things here:
1. Verify each key in response body does not have null value. Please note i'm sending one key with value as null and it is not returned in response.
2. The value sent in request body for each key is value returned by same key in response body. For instance if "name" key has value "Amber Joseph" then response key "name" also returns "Amber Joseph". But i want to do it for each key. Also Keys can defer everytime for instance i might or might not send it with "name" key hence i need a generic solution that applies to whatever key value pairs i send.
I'm able to loop through by using:
let jsonData = pm.response.json();
let dKey = Object.keys(jsonData);
let dValue = Object.values(jsonData);
for(var i = 0; i < dV.length; i++ ){
pm.expect(dV[i]).to.not.eql(null);
}
But this does not check nested key value pair individually.I specially want to check each key value pair inside the "data" object. Any help would be appreciated.
Thanks
You can grab the JSON data from the request like this:
const requestJson = JSON.parse(pm.request.body.raw);
(This assumes you're using a RAW body in Postman.)
Then, you can compare the response's data fields with the original request's data fields:
const requestJson = JSON.parse(pm.request.body.raw);
const responseJson = pm.response.json();
for (const [reqKey, reqValue] of Object.entries(requestJson.data)) {
pm.expect(responseJson.data[reqKey]).to.eql(requestJson.data[reqKey]);
}
From there, you can add whatever checks you want to do on the rest of the response.
I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I've a basic model where I would like to implement an endpoint that is capable to return subset of list back when we pass in some string param, and not sure how to go about doing it.
here is json file:
var user = [
{"id": "1", "name": "subash", "age": "22", "occupation": "doctor"},
{"id": "2", "name": "alex", "ip": "33", "occupation": "engineer"},
{"id": "3", "name": "darran", "ip": "18", "occupation": "singer"}
];
expected endpoint
app.get('/users/:someStringParam', user.findById);
expected response
Filters/returns rows of users who's name has letter 'a'.
I've looked at app.param() method of express framework but not sure how to go about!
The :parameter will be listed as part of req.params you can then use it to filter your array.
app.get('/agent/:letter', function (req, res, next) {
var containsLetter = new RegExp(req.pararms.letter);
res.json(users.filter(function (user) {
return containersLetter.test(user.name);
});
});