Node.js JSON extract certain data - json

I'm trying to get certain data from a json link:
bittrex.com/api/v1.1/public/getticker?market=BTC-DRS
in my node IRC bot using:
https://www.npmjs.org/package/node.bittrex.api
Part of the code:
var url = ('https://bittrex.com/api/v1.1/public/getticker?market=BTC-DRS');
bittrex.options({
'apikey' : settings.ticker.apikey,
'apisecret' : settings.ticker.secretkey,
'stream' : false,
'verbose' : false,
'cleartext' : true,
});
case 'ticker':
var user = from.toLowerCase();
bittrex.sendCustomRequest(url, function(ticker, err) {
if(err) {
winston.error('Error in !ticker command.', err);
client.say(channel, settings.messages.error.expand({name: from}));
return;
}
winston.info('Fetched Price From BitTrex', ticker);
client.say(channel, settings.messages.ticker.expand({name: user, price: ticker}));
});
break;
It works but outputs in IRC
[1:21am] <nrpatten> !ticker
[1:21am] <DRSTipbot> nrpatten The current DRS price at BitTrex {"success":true,"message":"","result":{"Bid":0.00000155,"Ask":0.00000164,"Last":0.00000155}}
I have used a couple of things to get it to show only "Last" from the reply but i keep getting errors.
Or get certain data from https://bittrex.com/api/v1.1/public/getmarketsummaries
Like any info i want from:
{"MarketName":"BTC-DRS","High":0.00000161,"Low":0.00000063,"Volume":280917.11022708,"Last":0.00000155,"BaseVolume":0.33696054,"TimeStamp":"2014-10-04T15:14:19.66","Bid":0.00000155,"Ask":0.00000164,"OpenBuyOrders":33,"OpenSellOrders":138,"PrevDay":0.00000090,"Created":"2014-06-18T04:35:38.437"}
Thanks for any help

Assuming you've parsed the JSON (e.g. via JSON.parse(str);), you just use whatever property name you want to get at. For example:
var info = JSON.parse('{"MarketName":"BTC-DRS","High":0.00000161,"Low":0.00000063,"Volume":280917.11022708,"Last":0.00000155,"BaseVolume":0.33696054,"TimeStamp":"2014-10-04T15:14:19.66","Bid":0.00000155,"Ask":0.00000164,"OpenBuyOrders":33,"OpenSellOrders":138,"PrevDay":0.00000090,"Created":"2014-06-18T04:35:38.437"}');
console.log(info.Bid);
Also, on an unrelated matter, typically callback parameters follow the error-first format (e.g. (err, result) instead of (result, err)) in order to be consistent with node core and most other modules on npm.

Related

How can I add another prefix to the bot run by the following code?

I'm making a discord bot but I'm trying to use 2 prefix's (G! and g!) as its case sensitive but I cant figure out how to make a 2nd prefix for it to work.
I have tried to separate strings with a comma between 2 strings but I got error codes.
DETECTS WETHER MESSAGE HAS PREFIX (IN DIFFERENT FILE)
module.exports = (client, message) => {
// Ignore all bots
if (message.author.bot) return;
// Ignore messages not starting with the prefix (in config.json)
if (message.content.indexOf(client.config.prefix) !== 0) return;
CONFIG FILE
{
"token": "xxx",
"prefix": "G!",
"prefix2": "g!",
"everyoneMention": true,
"hostedBy": true
}

POSTMAN - Save a property value from a JSON response

I am new to both JSON and Postman(as of yesterday).
I'm trying to do something very simple, I've created a GET request which pulls in a list of forms in a JSON response. I want to take this response and get the first "id" token and place it in a variable.
I am using a global variable but would like to use a collection variable if possible. Either way here is what I am doing.
I've tried several things, most recently this:
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("id", jsonData.args.id);
As well as this:
pm.test("GetId", function () {
var jsonData = pm.response.json();
pm.globals.set("id", jsonData.id);
});
Response code looks like this:
{
"forms":[
{
"id":"3197239",
"created":"2018-09-18 11:37:39",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Contact Us",
"num_columns":"2",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:02:13",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
},
{
"id":"3197245",
"created":"2018-09-18 11:42:02",
"db":"1",
"deleted":"0",
"folder":"151801",
"language":"en",
"name":"Football Draft",
"num_columns":"1",
"submissions":"0",
"submissions_unread":"0",
"updated":"2018-09-18 12:11:54",
"viewkey":"xxxxxx",
"views":"1",
"submissions_today":0,
"url":"https://xxxxxxxxx",
"data_url":"",
"summary_url":"",
"rss_url":"",
"encrypted":false,
"thumbnail_url":null,
"submit_button_title":"Submit Form",
"inactive":false,
"timezone":"US/Eastern",
"permissions":150
}
]
}
This would get the first id:
pm.globals.set('firstId', _.first(pm.response.json().forms).id)
That would get the first in the array each time so it would set a different variable it that response changed.
The test that you created was nearly there but the reference needed to go down a level into the forms array:
pm.test("GetId", function () {
var jsonData = pm.response.json()
pm.expect(jsonData.forms[0].id).to.equal("3197239")
pm.globals.set("id", jsonData.forms[0].id)
})
The [0]is referencing the first id in the first object within the array. For example [1] would get the second one and so on.
You currently cannot set a collection level variable using the pm.* API - These can only be added manually and referenced using the pm.variables.get('var_name') syntax.
Edit:
In the new versions of the desktop app you can set variables at the Collection level using pm.collectionVariables.set().
Based on the name or any other attribute if you want to set the id as a global variable then this is the way.
for(var i=0; i<jsonData.forms.length; i++)
{
if (jsonData.forms[i].name==="Contact Us")
{
pm.environment.set("id", jsonData.forms[i].id);
}
}

Count how many times a specific json/word appears

If I have a website that contains JSON with multiple "usrId":, how can I count how many times this exists? I do not know if it's better to count JSON objects or just count how many times that word exists on the webpage, also I wouldn't know how to get started, how can I do this?
request(getusr, function(err, res, body) {
let json = JSON.parse(body);
let usramount = // count how many times usrId appears
})
Example json:
{
"id":"example",
"usrId":"example"
},
{
"id":"example"
"usrId":"example",
},
(body.match(/"usrId":/g) || []).length;
should do the trick.

Consuming MySql Procedure out parameter which contains # in node js

I'm having issues with consuming Out Parameters from mySql in node JS when they contain #, I've searched for similar question but can't see any answers to my specific question:
Here's the procedure (not my code)
CREATE PROCEDURE `getuser`(IN `p_googleemail` varchar(64),
out `p_userjson` json)
SET #'p_userJSON' =
(
SELECT json_object('email', USER.email, 'lastName', USER.lastname, 'firstName', USER.firstname )
FROM test.USER
WHERE email = p_googleemail);
select #p_userJSON;
end
Here is a snippet of my Node Code:
/* GET users listing. */
router.get('/', function(req, res, next) {
getConnection(function(err, con) {
googleEmail ='test#gmail.com';
que = 'CALL test.getUser(?, #p_userJSON);';
con.query(que,[googleEmail], function(err, results) {
if (err) throw err;
con.release();
res.send(results);
});
});
});
This is the response:
[
[{
"#p_userJSON": "{\"email\": \"test#gmail.com\", \"lastName\": \"test\", \"firstName\": \"test\"}"
}],
{
"fieldCount": 0,
"affectedRows": 0,
"insertId": 0,
"serverStatus": 34,
"warningCount": 1,
"message": "",
"protocol41": true,
"changedRows": 0
}
]
How do I return the results from #p_userJSON as part of my rest service? I understand I'll have to unescape the json from the out param but I can't even return the #p_userJSON value.
Many thanks!
Edit:
My hack to get around the issue for the minute, this not the full code as got some error handling if there are no results (probably a better way but I've only been using js for a few weeks)
var datapackstr = JSON.stringify(results[0]);
var datapack = JSON.parse(JSON.parse(datapackstr.substring((datapackstr.lastIndexOf('#p_userJSON') + 12) + 1).slice(0, -2)));
Even though this thread is 6 years old I came across basically the same issue with the #. The problem is with the JSON string that's being returned and JSON.parse's ability to deal with the stirngs in #p_userJSON.
The below JSON string works as expected.
var result = '[[{"#p_userJSON": "{\\\"email\\\": \\\"test#gmail.com\\\", \\\"lastName\\\": \\\"test\\\", \\\"firstName\\\": \\\"test\\\"}"}],{"fieldCount": 0,"affectedRows": 0,"insertId": 0,"serverStatus": 34,"warningCount": 1,"message": "","protocol41": true,"changedRows": 0}]';
var res = JSON.parse(result);
console.log(res[0][0]['#p_userJSON']);
You can see a working example in a node fiddle here.
I did need to make some manual changes to the JSON. Remember that JSON.parse won't throw an error when it fails to return an actual JSON object it will simply return an object for each character in the input string.
You can find more info about the JSON.parse function here.

In watson conversation how to extract multiple values entered in input text

Iam working on an application where I display products in my inventory based on the user's "price range"..
I need to know how to extract the values (prices) entered in the input text.
I tried using the system entities #sys-currency & #sys-number but I can extract only one value(the first value)..
example:
the user asks to "display products between $200 and $500"
how can i extract both the values to be compared with the individual products prices and display relevant products..
suggestions appreciated..
In the node in watson conversation you can access entities as array. In your case it will be:
Currency 1: <? entities['sys-currency'] != null && entities['sys-currency'].size()> 0 ? entities['sys-currency'][0].value : "---" ?>; Currency 2: <? entities['sys-currency'] != null && entities['sys-currency'].size()> 1 ? entities['sys-currency'][1].value : "---" ?>
You need to add proper null checks and checks if array has more that one entered currency
If you're using nodejs, based on conversation-simple example from IBM Developers, you can do something like:
And the Node:
Code for access this values:
function updateMessage(input, data, req, res) {
console.log("Entties: "+JSON.stringify(data.entities));
//200 and 500 do something
if (data.entities[0].value == '200' && data.entities[1].value == '500') {
console.log("User choice value:" + data.entities)
// showProducts(data, req, res); do something inside this function
// or paste your code for do something here
}
Debugg:
Obs.: If the user types only one value (#sys-currency) you'll need to create one if with one condition, and get this value for do something within your application with my example:
data.entities //if have one value
data.entities[i] //Watson return some array if have more than 1 value
One good idea is use the context variable and join for get all values, like:
{ "context": {
"result": "<? #sys-currency ?>"
}
},
If you passing in the context all items which in stock and you want to have output like We have X,Y,Z in stock, then you can create output in Watson
<? context.results.join(', ') ?> //all values return
Important: You need to access the data return from the Watson Conversation call (conversation.message) for access all values like entities, intents and context variables, among others. Like:
conversation.message(payload, function (err, data) {
console.log(data)
if (err) {
return res.status(err.code || 500).json(err);
}
}