Right now , I am working on a project. I have to build some rest full api's for android application using Woo-Commerce CLIENT REST API.
Everything is working fine, but the data i'm getting is unnecessary. So can anybody tell me, how to overcome from this problem.
e.g. I am getting this data
{
product_categories: [
{
id: 8,
name: "Cakes",
slug: "cakes",
parent: 0,
description: "Love is like a good cake; you never know when it's coming, but you'd better eat it when it does!",
count: 11
},
{
id: 9,
name: "Breads",
slug: "breads",
parent: 0,
description: "All sorrows are less with bread. ",
count: 3
},
{
id: 10,
name: "Pastries",
slug: "pastries",
parent: 0,
description: "I'm not a vegetarian! I'm a pastries-ian!",
count: 6
}
but i do not want slug,parent, description parameters.
Thanks in advance.
Your Problems is " " missing in key Ex: "ID", "name" and
You use this function json_pretty() for json format.
function json_pretty($json, $html = false) {
$out = ''; $nl = "\n"; $cnt = 0; $tab = 4; $len = strlen($json); $space = ' ';
if($html) {
$space = ' ';
$nl = '<, $html = false)br/>';
}
$k = strlen($space)?strlen($space):1;
for ($i=0; $i<=$len; $i++) {
$char = substr($json, $i, 1);
if($char == '}' || $char == ']') {
$cnt --;
$out .= $nl . str_pad('', ($tab * $cnt * $k), $space);
} else if($char == '{' || $char == '[') {
$cnt ++;
}
$out .= $char;
if($char == ',' || $char == '{' || $char == '[') {
$out .= $nl . str_pad('', ($tab * $cnt * $k), $space);
}
}
return $out;
}
How to user this function ?
$pre = '{"status": 1,"message": "My Collection downloaded successfully.","myCollections":';
$postd = ' }';
$jsa_data = json_encode($res_arr); // pass your Array
echo $finalJson = json_pretty($pre.$jsa_data.$postd);
Out put
{
"status": 1,
"message": "All Post downloaded successfully",
"postData": [
{
"id": 8,
"name": "Cakes",
"slug": "cakes",
"parent": 0,
"description": "Love is like a good cake; you never know when it's coming, but you'd better eat it when it does!",
"count": 11
},
{
"id": 9,
"name": "Breads",
"slug": "breads",
"parent": 0,
"description": "All sorrows are less with bread. ",
"count": 3
},
{
"id": 10,
"name": "Pastries",
"slug": "pastries",
"parent": 0,
"description": "I'm not a vegetarian! I'm a pastries-ian!",
"count": 6
}
]
}
Check it Json LINT http://jsonlint.com/
Related
I have the following object :
{
"db_credentials": {
"database": "greengrass",
"host": "localhost",
"password": "yZqXJzXHLUsLlPm",
"port": 7086,
"username": "greengrass"
},
"default_interval": 90000,
"fields_selected": [
{
"measurement": "ABPLCGD-GD_AB1AirFlowCalc",
"aggregation": "last",
"step": "10m",
"timeserie_physical": "null",
"timeserie_type": "null",
"timeserie_interpolation": "null",
"timeserie_unit": "null",
"timeserie_step": "10"
},
{
"measurement": "ABPLCGD-GD_AB1InletAirTempAct",
"aggregation": "last",
"step": "10m",
"timeserie_physical": "null",
"timeserie_type": "null",
"timeserie_interpolation": "null",
"timeserie_unit": "null",
"timeserie_step": "10"
}
]
}
and i wish to transform it into :
{
"db_credentials": {
"database": "greengrass",
"host": "localhost",
"password": "yZqXJzXHLUsLlPm",
"port": 7086,
"username": "greengrass"
},
"default_interval": 90000,
"fields_selected": [
{
"name": "ABPLCGD-GD_AB1AirFlowCalc",
"aggregation": {
"step": "10m",
"function": "last"
}
},
{
"name": "ABPLCGD-GD_AB1InletAirTempAct",
"aggregation": {
"step": "10m",
"function": "last"
}
}
]
}
i have tried multiple solution but this is the maximum where i can get :
jq ' .fields_selected = .fields_selected | map({name : .measurement , aggregation : {step: .step , function: .aggregation}})' config-it-client.json
but i got always this error that Cannot index number with string "measurement" and i cant figure out what i'm doing wrong
I'd use the following:
.fields_selected[] |= { name: .measurement, aggregation: { function: .aggregation, step } }
To get it working, you were just missing parens.
.fields_selected = .fields_selected | ...
means
( .fields_selected = .fields_selected ) | ...
It should be
.fields_selected = ( .fields_selected | ... )
This gives us
.fields_selected = (
.fields_selected |
map({
name: .measurement,
aggregation: {
function: .aggregation,
step: .step
}
})
)
Demo on jqplay
But we can improve this. foo = ( foo | ... ) can generally be written as foo |= ( ... ).
.fields_selected |= map({
name: .measurement,
aggregation: {
function: .aggregation,
step: .step
}
})
We could modify the objects in the fields array instead of the array itself.
.fields_selected[] |= {
name: .measurement,
aggregation: {
function: .aggregation,
step: .step
}
}
Finally, { foo: .foo, ... } can be shortened to { foo, ... }.
.fields_selected[] |= {
name: .measurement,
aggregation: {
function: .aggregation,
step
}
}
As a sh one-liner:
jq '.fields_selected[] |= { name: .measurement, aggregation: { function: .aggregation, step } }'
Demo on jqplay
I was able to figure out what i was doing wrong:
jq '.fields_selected = (.fields_selected | map({name : .measurement , aggregation : {step: .step , function: .aggregation}}))' config-it-client.json
I want to get all the products by range price with discount.
this is what it looks like in sql:
WHERE (
CASE WHEN p.discount IS NOT NULL THEN ROUND(
p.unit_price * (100 - p.discount) / 100, 1)
ELSE p0_.unit_price END ) >= :min
AND (
CASE WHEN p.discount IS NOT NULL THEN ROUND(
p.unit_price * (100 - p.discount) / 100, 1)
ELSE p0_.unit_price END ) <= :max
is there a way to do the same with range condition?
$fieldRange = new \Elastica\Query\Range('unitPrice', array('gte' => 300, 'lte' => 1500));
here is my config:
fos_elastica:
clients:
default: { url: '%env(ELASTICSEARCH_URL)%' }
indexes:
product:
properties:
unitPrice:
type: integer
discount:
type: keyword
attributeValues:
type: "nested"
properties:
value:
type: keyword
product:
type: keyword
persistence:
driver: orm
model: App\Entity\Product
provider: ~
listener: ~
finder: ~
here is the full query:
$query = new \Elastica\Query();
$query->setSize(0);
$boolQuery = new \Elastica\Query\BoolQuery();
/* filter checked */
$fieldQuery = new \Elastica\Query\Match();
$fieldQuery->setFieldQuery('attributeValues.value', 'Brand');
$domainQuery = new \Elastica\Query\Nested();
$domainQuery->setPath('attributeValues');
$domainQuery->setQuery($fieldQuery);
$fieldQuery2 = new \Elastica\Query\Match();
$fieldQuery2->setFieldQuery('attributeValues.value', 'Another Brand');
$domainQuery2 = new \Elastica\Query\Nested();
$domainQuery2->setPath('attributeValues');
$domainQuery2->setQuery($fieldQuery2);
$fieldRange = new \Elastica\Query\Range('unitPrice', array('gte' => 300, 'lte' => 1500));
$boolQuery->addMust($domainQuery);
$boolQuery->addMust($domainQuery2);
$boolQuery->addMust($fieldRange);
$query->setQuery($boolQuery);
$agg = new \Elastica\Aggregation\Nested('attributeValues', 'attributeValues');
$names = new \Elastica\Aggregation\Terms('value');
$cardinality = new \Elastica\Aggregation\Cardinality('unique_products');
$cardinality->setField('attributeValues.product');
$names->setField('attributeValues.value');
$names->setSize(100);
$names->addAggregation($cardinality);
$agg->addAggregation($names);
$query->addAggregation($agg);
$companies = $this->finder->findPaginated($query);
$asd = $companies->getAdapter()->getAggregations();
here is the result:
array(
"attributeValues" => array:2(
"doc_count" => 406,
"value" => array:3(
"doc_count_error_upper_bound" => 0,
"sum_other_doc_count" => 0,
"buckets" => array:42(
2 => array:3(
"key" => "Another Brand",
"doc_count" => 15,
"unique_products" => array:1(
"value" => 9
)
)
)
)
)
);
here is native request (just in case):
{
"size": 0,
"query": {
"bool": {
"must": [
{
"nested": {
"path": "attributeValues",
"query": {
"match": {
"attributeValues.value": {
"query": "Brand"
}
}
}
}
},
{
"nested": {
"path": "attributeValues",
"query": {
"match": {
"attributeValues.value": {
"query": "Another Brand"
}
}
}
}
},
{
"range": {
"unitPrice": {
"gte": 300,
"lte": 1500
}
}
}
]
}
},
"aggs": {
"attributeValues": {
"nested": {
"path": "attributeValues"
},
"aggs": {
"value": {
"terms": {
"field": "attributeValues.value",
"size": 100
},
"aggs": {
"unique_products": {
"cardinality": {
"field": "attributeValues.product"
}
}
}
}
}
}
}
}
a little explanation - I am making a smart filter that disables options when there are no products in it, which I calculate with this query. But I don't know how to calculate the price range with a discount (%) in elastica. I show how I do it in sql.
I have the following document,
{
"VehicleDetailId": 1,
"VehicleDetail": [
{
"Id": 1,
"Make": "BMW"
},
{
"Id": 1,
"Model": "ABDS"
},
{
"Id": 1,
"Trim": "5.6L/ASMD"
},
{
"Id": 1,
"Year": 2008
}
]
}
I want to give aliases for the array elements, something like this,
{
"VehicleDetailId": 1,
"Type": "VehicleDetail",
"VehicleDetail": [
{
"MakeId": 1,
"MakeValue": "BMW"
},
{
"ModelId": 1,
"ModelValue": "ABDS"
},
{
"TrimId": 1,
"TrimValue": "5.6L/ASMD"
},
{
"YearId": 1,
"YearValue": 2008
}
]
}
The following query seems to work fine, but since Id is common for all, it is repeating every time.
SELECT c.vehicleDetailId, ARRAY(SELECT v.Id AS MakeId, v.Make AS MakeValue,
v.Id AS ModelId, v.Model AS ModelValue,
v.Id AS TrimId, v.Trim AS TrimValue,
v.Id AS YearId, v.Year AS YearValue
FROM v IN c.VehicleDetail) AS VehicleDetail
FROM c
How should I write the query so that the Id does not repeat every time, and I can fetch an element from a specific position?
You could use UDF to implement your needs.
Udf code:
function userDefinedFunction(array){
var returnArray = [];
for(var i=0;i<array.length;i++){
var obj = array[i];
var map = {};
if(obj.Make){
map["MakeId"]= obj.Id;
map["MakeValue"]= obj.Make;
}else if(obj.Model){
map["ModelId"]= obj.Id;
map["ModelValue"]= obj.Model;
}else if(obj.Trim){
map["TrimId"]= obj.Id;
map["TrimValue"]= obj.Trim;
}else if(obj.Year){
map["YearId"]= obj.Id;
map["YearValue"]= obj.Year;
}
returnArray.push(map);
}
return returnArray;
}
Sql:
SELECT c.VehicleDetailId,udf.test(c.VehicleDetail) AS VehicleDetail
FROM c
Output:
I am trying to lock the keys in the custom keyboard so the user can tap multiple buttons in the custom keyboard before sending the message. The default is you tap a custom keyboard button and message is sent, like with trivia bot. Any ideas on how to do this or if it is even possible?
If I understood right, what you want to do is multiselect (checkbox); there is no such function in telegram, but you can implement it a bit differently.
First, you send message with inline buttons and empty checkboxes with some text:
switch ($callback_query){
case 'choose':
$inline_keyboard = [
[
['text'=>'☐ 1', 'callback_data'=>"n1"],
['text'=>'☐ 2', 'callback_data'=>"n2"],
['text'=>'☐ 3', 'callback_data'=>"n3"]
],
[
['text'=>'☐ 4', 'callback_data'=>"n4"],
['text'=>'☐ 5', 'callback_data'=>"n5"]
],
[
['text'=>'Next', 'callback_data'=>"$someData"]
]
];
$keyboard=["inline_keyboard"=>$inline_keyboard];
$replyMarkup = json_encode($keyboard);
sendMessage($chat_id_callback, "Lorem ipsum dolor sit amet.", $replyMarkup);
break;
// When user is clicking on the buttons You process it with another case with all possible buttons in it and using telegram api to editMessageReplyMarkup
case "n1":
case "1":
case "n2":
case "2":
case "n3":
case "3":
case "n4":
case "4":
case "n5":
case "5":
$empty_checkbox = "☐";
$galochka = "✔";
if (substr($data,0,1)== "n"){
$is_checked = TRUE;
} else {
$is_checked = FALSE;
}
if ($is_checked){
$what_is_checked = substr($data, 1);;
} else {
$what_is_checked = $data;
}
// $output is variable, in wich telegram data is stored, which came through webhook
$text1 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][0][0]['text'];
$text2 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][0][1]['text'];
$text3 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][0][2]['text'];
$text4 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][1][0]['text'];
$text5 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][1][1]['text'];
$room_callback_data1 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][0][0]['callback_data'];
$room_callback_data2 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][0][1]['callback_data'];
$room_callback_data3 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][0][2]['callback_data'];
$room_callback_data4 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][1][0]['callback_data'];
$room_callback_data5 = $output['callback_query']['message']['reply_markup']['inline_keyboard'][1][1]['callback_data'];
if ($what_is_checked == "1"){
if ($is_checked == TRUE) {
$text1 = $galochka . " 1";
$room_callback_data1 = "1";
} else {
$text1 = $empty_checkbox . " 1";
$room_callback_data1 = 'n2';
}
} elseif ($what_is_checked == "2"){
if ($is_checked == TRUE) {
$text2 = $galochka . " 2";
$room_callback_data2 = "2";
} else {
$text2 = $empty_checkbox . " 2";
$room_callback_data2 = 'n2';
}
} elseif ($what_is_checked == "3"){
if ($is_checked == TRUE) {
$text3 = $galochka . " 3";
$room_callback_data3 = "3";
} else {
$text3 = $empty_checkbox . " 3";
$room_callback_data3 = 'n3';
}
} elseif ($what_is_checked == "4"){
if ($is_checked == TRUE) {
$text4 = $galochka . " 4";
$room_callback_data4 = "4";
} else {
$text4 = $empty_checkbox . " 4";
$room_callback_data4 = 'n4';
}
} elseif ($what_is_checked == "5"){
if ($is_checked == TRUE){
$text5 = $galochka . " 5";
$room_callback_data5 = "5";
} else {
$text5 = $empty_checkbox . " 5";
$room_callback_data5 = 'n5';
}
}
$inline_keyboard = [
[
['text'=>$text1, 'callback_data'=>$room_callback_data1],
['text'=>$text2, 'callback_data'=>$room_callback_data2],
['text'=>$text3, 'callback_data'=>$room_callback_data3]
],
[
['text'=>$text4, 'callback_data'=>$room_callback_data4],
['text'=>$text5, 'callback_data'=>$room_callback_data5]
],
[
['text'=>'Next', 'callback_data'=>"remont"]
]
];
$keyboard=["inline_keyboard"=>$inline_keyboard];
$replyMarkup = json_encode($keyboard);
editMessageReplyMarkup($chat_id_callback, $message_id, $replyMarkup);
break;
}
In the second case, you are just checking which button was pressed and simply change empty box on check mark.
Also, you need to use answerCallbackQuery, to work properly:
function send_answerCallbackQuery($callback_query_id, $text ='', $alert = 0){
file_get_contents($GLOBALS['api']."/answerCallbackQuery?callback_query_id=".$callback_query_id . '&text=' . $text . '&show_alert=' . $alert);
}
if (isset($output['callback_query'])) {
send_answerCallbackQuery($output['callback_query']['id']);
}
It's a default behavior to preserve custom keyboard unless you set one_time_keyboard = True or return a ReplyKeyboardHide to a user.
See docs: https://core.telegram.org/bots/api#replykeyboardmarkup
Also you can send the same keyboard in a reply message every time you want to make sure the keyboard is displayed.
var productDB = new Meteor.Collection('products'); //Want to insert into this DB
var ProductParameters = nodeDB.find({"ACTIVE" : 1, "VARIENTS.ACCESS" : "PUBLIC"}, { "VARIENTS.NAME": 1, _id : 0 } ); //Taking Paramters from Another DB
Template.dpVar.events = {
'click .addProduct' : function (e) {
e.preventDefault();
ProductParameters.forEach(function(){ **//This is my Question.How to insert into productDB the key values as {ProductParameters: Val of ProductParameters}**
console.log(ProductParameters);
var pvariable = {
pvariable: tmpl.find("#ProductParameters").value
};
productDB.insert(pvariable);
});
}
};
Problem:
I have created form from the Parameters of nodeDB.
I want to store the data from this new form in a new DB productDB.
I want to run a loop where all the ProductParameters are read from nodeDB and their corresponding values inserted in form by user are pushed into ProductDB as new Entry.
EDIT:
NodeDB has Templates:
db.nodes.insert([
{
"GEOLOCATION": {
"GEO_CODE": [],
"ACTIVE_GEOLOCATION": false
},
"META": {
"CATEGORY": "levis",
"DESCRIPTION": "dsad",
"PRIVACY": "PUBLIC",
"TEMPLATE_NAME": "B",
"TEMPLATE_GROUP": "Product",
"KEYWORDS": [
"sda"
],
"CREATEDBY": "",
"SUBCATEGORY": "Blue",
"PRODUCT_TEMPLATE_TYPE": "Consumable",
"UOM": "",
"TEMPLATE_SUBGROUP": ""
},
"VARIENTS": [
{
"COMMENT": "Demo",
"INDEX": 0,
"NAME": "Brand",
"IS_PARENT": false,
"DATATYPE": "Text",
"ACCESS": "PUBLIC",
"PARENT_VARIENT": "Parem",
"TYPE": "PERMANENT"
}
]
}
])
The form is generated only from the VARIENTS
The ProductDB would be {key,value} ={VARIENTS.NAME,value from UI}
There can be multiple VARIENTS as this contains only one "Brand"
instead of
var ProductParameters = nodeDB.find({"ACTIVE" : 1, "VARIENTS.ACCESS" : "PUBLIC"}, { "VARIENTS.NAME": 1, _id : 0 } );
add .fetch() at the end
var ProductParameters = nodeDB.find({"ACTIVE" : 1, "VARIENTS.ACCESS" : "PUBLIC"}, { "VARIENTS.NAME": 1, _id : 0 } ).fetch();