Why data is doubled, how I can fix it? - javascript

Good afternoon.
I have required json, which contains the basic template for the layout of Adaptive Cards (bot framework).
Here's this json:
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0",
"type": "AdaptiveCard",
"speak": "",
"body": [
{
"type": "TextBlock",
"horizontalAlignment": "center",
"text": "Все машины",
"weight": "bolder",
"isSubtle": false
},
{
"type": "TextBlock",
"text": "Внимание, вы вошли в режим тендера.",
"separator": true
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Подтвердить лот(ы)",
"data": {
"msteams": {
"type": "messageBack",
"displayText": "Идет подтверждение ваших лотов, ожидайте!",
"text": "/accept",
"value": "{\"x\": \"bfVal\", \"y\": \"from value\"}"
}
}
},
{
"type": "Action.Submit",
"title": "Отменить все лоты",
"data": {
"x": "123",
"msteams": {
"type": "messageBack",
"displayText": "Идет отменение ваших лотов, ожидайте!",
"text": "/cancel",
"value": "{\"bfKey\": \"bfVal\", \"conflictKey\": \"from value\"}"
}
}
}
]
}
I also have a loop that takes data from my source and forms another json from it.
try {
// Pull in the data from Microsoft Graph.
const client = new SimpleGraphClient(tokenResponse.token);
const me = await client.getList();
var i = 0;
while (i < me['value'].length) {
feed = {
"type": "ColumnSet",
"separator": true,
"columns": [
{
"type": "Column",
"width": 1,
"items": [
{
"type": "TextBlock",
"text": "Продукт",
"isSubtle": true
},
{
"type": "TextBlock",
"size": "extraLarge",
"color": "accent",
"text": me.value[i].fields.Good,
"spacing": "none"
},
{
"type": "TextBlock",
"text": "Дата: " + dateFormat(me.value[i].fields.ShipmentDateTime, 'dd-mm-yyyy'),
"spacing": "yes"
}
]
},
{
"type": "Column",
"width": "auto",
"items": [
{
"type": "TextBlock",
"text": " "
},
{
"type": "Image",
"url": "https://png.pngtree.com/svg/20170614/engine_oil_410031.png",
"size": "medium",
"spacing": "yes"
},
{
"type": "TextBlock",
"text": " ID: " + me.value[i].fields.id,
"value": me.value[i].fields.id
}
]
},
{
"type": "Column",
"width": 1,
"items": [
{
"type": "TextBlock",
"horizontalAlignment": "right",
"text": "RUB",
"isSubtle": true
},
{
"type": "TextBlock",
"horizontalAlignment": "right",
"size": "extraLarge",
"color": "accent",
"text": me.value[i].fields.PricePerTon,
"spacing": "none"
},
{
"type": "Input.Toggle",
"title": "Приобрести лот",
"valueOn": "true",
"valueOff": "false",
"id": "buyGood",
"spacing": "yes"
}
]
}
]
}
tender.body.push(feed);
i++;
}
Then I combine these json.
This works well, but when you retrieve the data again, the data is doubled.
How can this be resolved?
Thanks in advance.

It looks like every time you create a new card, you are appending the JSON object you created in the while loop to your required JSON object. Consequently, the next time you try to create a new card, the data from the previous request is still stored in your required JSON object. To avoid this, create a copy of the required JSON Object and store it in a different variable before your while loop. You can use JSON.parse(JSON.stringify(obj)) to create a copy of a JSON Object.
Your code should look something like this:
// create a copy of the required JSON Object
// and store it in a new variable
const card = JSON.parse(JSON.stringify(tender));
var i = 0;
while (i < me['value'].length) {
let feed = {
"type": "ColumnSet",
"separator": true,
...
}
// push feed to `card` instead of `tender`
card.body.push(feed);
i++;
}
...
// send `card` to user instead of `tender`
await turnContext.sendActivity({
text: "Double Data Card",
attachments: [CardFactory.adaptiveCard(card)]
});

Related

How to print huge number of items from the json array

This is my json format with that im displaying my array items like this.
If i have more items in my array mean how can i print that all using for loop or is there any method available to print all that items in an array?
{
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
}
<script>
const api_url = "API URL";
async function get_data_from_api() {
const response = await fetch(api_url);
var data = await response.json();
var track = data["workers"][2]["id"];
document.getElementById('demo2').innerHTML = track ;
}
</script>
Reference:
JSON.stringify()
const o = {
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
};
output.innerHTML = JSON.stringify(o, undefined, 2);
<pre id="output"></pre>

How to dynamically create and iterate Json Object inside a Json Array using Postman - Javascript

I have a payload like mentioned below :
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil’sFood"
}
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "PowderedSugar"
},
{
"id": "5006",
"type": "ChocolatewithSprinkles"
},
{
"id": "5003",
"type": "Chocolate"
},
{
"id": "5004",
"type": "Maple"
}
]
}
**I want to increment the json objects dynamically(it can be a duplicate as well) which is inside the array topping based on the array size. For example if mention the array size as topping[10] it is suppose to create a payload of 10 objects and push those 10 objects of similar type inside the array topping ** Is it possible to dynamically create json objects and post the request in postman??
Kind note : The size of the array should be parameterized. Please let me know.
Please find the image highlighted in green. I want to dynamically increase the payload(topping array size based on the index using postman
You could do this:
Tab Pre-request
let req = {
"id": "0001",
"type": "donut",
"topping": []
};
let numberOfTopping = 5;
for (let i = 0; i < numberOfTopping; i++) {
let toppingItem = {
"id": `${_.random(5001, 5010)}`,
"type": `${_.sample(["Glazed", "Sugar", "None"])}`
};
req.topping[i] = toppingItem;
}
pm.variables.set("req", JSON.stringify(req));
Tab body
Result
{
"id": "0001",
"type": "donut",
"topping": [
{
"id": "5006",
"type": "Glazed"
},
{
"id": "5001",
"type": "Sugar"
},
{
"id": "5006",
"type": "Glazed"
},
{
"id": "5006",
"type": "None"
},
{
"id": "5008",
"type": "Sugar"
}
]
}

validate json object with varying properties

I have json object whose property values are unique and can be anything;
{
"cat1": {
"name": "kitty",
"type": "animal",
"color": "ginger"
},
"dog2": {
"name": "ripple",
"type": "animal",
"color": "black"
},
"book10": {
"name": "myBook",
"type": "book",
"color": "NA"
},
"orange6": {
"name": "NA",
"type": "fruit",
"color": "orange"
},
"pig1":{
"name": "spring",
"type": "animal",
"color": "pink"
}
}
Now I'm confused how to write its validation schema. Does anybody know how to do it?
var mySchema = {
"type": "object",
"properties": {
// no idea how to check varying properties like cat1, dog2, etc. which might change next time
}
}
You can try this
var mySchema = {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"name": { "type": "string"},
"type": { "type": "string"},
"color": { "type": "string"},
}
}
}
ref: JSONSchema how to define a schema for a dynamic object

undefined error while while accessing JSON data

$http({
method: 'GET',
// url: "https://na30.salesforce.com/services/data/v36.0/query?q=SELECT+id,+name,+Product2.Name,+Product2.Description,+Product2Id,+Pricebook2Id,+Product2.Family,+Product2.Product_Image_URL__c,+Product2.Product_Image__c,+Pricebook2.name+from+PricebookEntry+where+(Pricebook2.Id+=+'01s360000049JQh'+and+Product2.Family+=+'CURRIES')",
url: $scope.finalurl,
headers: { 'Content-Type': 'application/json' ,
'Authorization' : $scope.result1 }
}).success(function(response) {
$scope.result= response.totalSize;
// $scope.size = response.
// alert(" Products records captured");
// alert($scope.result);
var y =response.records;
alert(y);
localStorage.setItem("offlinecurries1",JSON.stringify(y));
var x =localStorage.getItem("offlinecurries1");
alert(JSON.stringify(x[0].Name));
getting undefined error in the above alert
my response data is
{
"totalSize": 497,
"done": true,
"records": [{
"attributes": {
"type": "PricebookEntry",
"url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de83AAA"
},
"Id": "01u36000001de83AAA",
"Name": "P-0025",
"Pricebook2Id": "01s36000004AGVLAA4",
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v36.0/sobjects/Product2/01t36000001To1lAAC"
},
"Product_Image_URL__c": null,
"Description": "ACHAPPAM175GMS X12PKT",
"Family": null,
"Product_Image__c": "<img src=\" \" alt=\"Not Avaialble\" height=\"50\" width=\"50\" border=\"0\"/>"
},
"Product2Id": "01t36000001To1lAAC",
"Pricebook2": {
"attributes": {
"type": "Pricebook2",
"url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4"
},
"Name": "UK Pricebook"
}
}, {
"attributes": {
"type": "PricebookEntry",
"url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de84AAA"
},
"Id": "01u36000001de84AAA",
"Name": "P-0026",
"Pricebook2Id": "01s36000004AGVLAA4",
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v36.0/sobjects/Product2/01t36000001To1mAAC"
},
"Product_Image_URL__c": null,
"Description": "ADA RICE 200 x 30",
"Family": null,
"Product_Image__c": "<img src=\" \" alt=\"Not Avaialble\" height=\"50\" width=\"50\" border=\"0\"/>"
},
"Product2Id": "01t36000001To1mAAC",
"Pricebook2": {
"attributes": {
"type": "Pricebook2",
"url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4"
},
"Name": "UK Pricebook"
}
}]
}
var x =localStorage.getItem("offlinecurries1");
this line returns a string!
you need to parse the string into a json object, add this line right after
var x =localStorage.getItem("offlinecurries1");
x = JSON.parse(x)
Try this. You need to strigify when saving and while retrieving you need to parse the json using JSON.parse so it can be converted back to array.
var json = { "totalSize": 497, "done": true, "records": [{ "attributes": { "type": "PricebookEntry", "url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de83AAA" }, "Id": "01u36000001de83AAA", "Name": "P-0025", "Pricebook2Id": "01s36000004AGVLAA4", "Product2": { "attributes": { "type": "Product2", "url": "/services/data/v36.0/sobjects/Product2/01t36000001To1lAAC" }, "Product_Image_URL__c": null, "Description": "ACHAPPAM175GMS X12PKT", "Family": null, "Product_Image__c": "" }, "Product2Id": "01t36000001To1lAAC", "Pricebook2": { "attributes": { "type": "Pricebook2", "url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4" }, "Name": "UK Pricebook" } }, { "attributes": { "type": "PricebookEntry", "url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de84AAA" }, "Id": "01u36000001de84AAA", "Name": "P-0026", "Pricebook2Id": "01s36000004AGVLAA4", "Product2": { "attributes": { "type": "Product2", "url": "/services/data/v36.0/sobjects/Product2/01t36000001To1mAAC" }, "Product_Image_URL__c": null, "Description": "ADA RICE 200 x 30", "Family": null, "Product_Image__c": "" }, "Product2Id": "01t36000001To1mAAC", "Pricebook2": { "attributes": { "type": "Pricebook2", "url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4" }, "Name": "UK Pricebook" } }] };
var y = json.records;
alert(y);
localStorage.setItem("offlinecurries1", JSON.stringify(y));
var x = JSON.parse(localStorage.getItem("offlinecurries1"));
alert(x[0].Name);

Why does my Preview Window doesn't show FormElement Content

I am trying to add a sap.ui.layout.form.Form with FormContainer and FormElements to a Preview Dialog. However, my Form and its Elements doesn't get rendered.
Click Here:
{
"Type": "sap.ui.core.mvc.JSONView",
"content": [
{
"Type": "sap.m.Button",
"id": "testitemid0",
"text": "MyTestButton",
"press": "asdf"
},
{
"Type": "sap.ui.layout.form.Form",
"id": "testitemid1",
"formContainers": [
{
"Type": "sap.ui.layout.form.FormContainer",
"id": "testitemid2",
"formElements": [
{
"Type": "sap.ui.layout.form.FormElement",
"id": "testitemid3",
"label": {
"Type": "sap.m.Label",
"id": "testitemid4",
"text": "My Test Label"
},
"fields": [
{
"Type": "sap.m.Input",
"id": "testitemid5",
"value": "My Test Input",
"placeholder": ""
}
]
}
]
}
]
}
]
}
Any Idea why it doesn't render the Form?
My sap.ui.layout.form.Form-Element simply lacks a layout:
{
"Type": "sap.ui.layout.form.Form",
"id": "testitemid1",
"layout": {
"Type": "sap.ui.layout.form.GridLayout"
},
...
}
JSBin

Categories

Resources