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.
Related
I am having some difficulty crafting a query for nested data in cosmosDB.
Say I have data stored in this structure:
{
id:"1234",
data:{
people:{
"a826bbc5-add9-42d8-ba52-f5de52973556":{
first_name: "Kyle"
},
"efb119d-9f12-4d11-a7e1-38e4719a699c":{
first_name: "Bob"
},
"b402faac-d1ba-4317-9ba6-673c76a8fc37":{
first_name: "Jane"
}
}
}
}
Now I want to write a query that would return all of the people with the first name of "Bob"
I need something like:
Select * from c where c.data.people[*].first_name = "Bob";
Notice that the "people" object is an actual JSON object not a JSON array, so no array_contains, I need basically the JSON obj equivalent.
I've looked around and can't seem to find the appropriate query for this common use-case.
Anyone know how I can accomplish this query?
Since the key of people objects is random,i'm afraid you can't query it with normal sql.I tried to implement your needs with UDF in cosmos db.
Udf code:
function userDefinedFunction(peopleObj){
var returnArray = [];
for(var key in peopleObj){
if (peopleObj[key].first_name == "Bob"){
var map = {};
map[key] = peopleObj[key];
returnArray.push(map);
}
}
return returnArray;
}
Sql:
SELECT udf.test(c.data.people) as BobPeople FROM c
Sample data:
Output:
Marked Jay's answer as the accepted answer as I ended up using udfs - I'll post the function I ended up using and the query for anyone looking for something a little more generic.
function userDefinedFunction(properties, fieldName, filedValue){
for(var k in properties){
if(properties[k][fieldName] && properties[k][fieldName] == filedValue)
return true;
}
return false;
}
with a query of:
select * from c where udf.hasValue(c.data.people,"first_name","Bob")
Can you please suggest how to get select fields from find method ?
e.g
let params = {
limit,
offset,
query: request
};
this.adapter.find(params)
Here, this will return all fields but instead of this I need only account_id from the resultset. I've already tried with fields inside params as well as settings{ fields: ["accout_id", "username"]} but doesn't work.
e.g
fields: ["account_id"]
Please guide me.
Thanks
Yes... I got the solution. I've used 'this.model' intead of 'this.adapter' like following way.
let params = {
limit,
offset,
query: request
};
this.model.find({
attributes: ['account_id'],
where : first_name : {
$like: '%Adam%'
}
})
I am creating a API using nodejs. The API takes request and responds in JSON
For example:
I have a table QUESTION in my database so a GET request to endpoint http://localhost/table/question will output the table in JSON format.
However there is a problem when performing JOINS
Considering tables QUESTION and CHOICE. A question has many choices (answers) their join will be
Table:
I am trying to convert to something like this
{
"0":{
"QUESTION":"If Size of integer pointer is 4 Bytes what is size of float pointer ?",
"OPTION":{
"A":"3 Bytes",
"B":"32 Bits",
"C":"64 Bits",
"D":"12 Bytes"
}
},
"1":{
"QUESTION":"Which one is not a SFR",
"OPTION":{
"A":"PC",
"B":"R1",
"C":"SBUF"
}
},
"2":{
"QUESTION":"What is Size of DPTR in 8051",
"OPTION":{
"A":"16 Bits",
"B":"8 Bytes",
"C":"8 Bits"
}
},
"3":{
"QUESTION":"Is to_string() is valid builtin function prior to c++11 ? ",
"OPTION":{
"A":"Yes",
"B":"No"
}
}
}
The obvious solution is to parse it query using JOIN and convert it to JSON.
Is there any more efficient way to do it?
In MySQL you can achieve this with group_concat
tablenames, fieldnames, etc are pure fantasy :-)
select
q.text as question,
group_concat(answer.label, ';;;') as labels,
group_concat(answer.text, ';;;') as answers
from
question as q
join answer as a on a.quesion = q.id
group by
q.text
And then in your application (nodejs)
let resultRows = callSomeFunctionsThatReturnesAllRowsAsArray();
let properStructure = resultRows.map(row => {
let texts = row.answers.split(';;;');
return {
question: row.question,
options: row.labels.split(';;;').map((label, index) => {label: label, answer: texts[index]});
}
});
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);
}
}
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.