full json is
{
"id": "70dec1ac-345f-4b94-b255-b09c5ab1b522",
"name": "card",
"auto": true,
"contexts": [],
"responses": [
{
"resetContexts": false,
"affectedContexts": [],
"parameters": [],
"messages": [
{
"type": 1,
"platform": "facebook",
"title": "this is the title updated",
"subtitle": "this is the subtitle",
"imageUrl": "https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg",
"buttons": [
{
"text": "this is the button"
},
{
"text": "this is also a button"
}
],
"lang": "en"
},
{
"type": 0,
"speech": []
}
],
"defaultResponsePlatforms": {},
"speech": []
}
],
"priority": 500000,
"cortanaCommand": {
"navigateOrService": "NAVIGATE",
"target": ""
},
"webhookUsed": false,
"webhookForSlotFilling": false,
"lastUpdate": 1530197695,
"fallbackIntent": false,
"events": [],
"userSays": [
{
"id": "528c22d4-49d7-4ab9-a8db-fcd84d57694b",
"data": [
{
"text": "card"
}
],
"isTemplate": false,
"count": 0,
"updated": 1530196620,
"isAuto": false
}
],
"followUpIntents": [],
"templates": []
}
I am actually making a chatbot for wordpress to communicate with api.ai or dialogflow
The code I am currently using to display a card is the following:
var html = "<div class=\"myc-conversation-bubble myc-conversation-response myc-is-active myc-image-response\"><img src=\"" + imageUrl + "\"/></div>";
html+="<div class=\"myc-card-title\">" + title + "</div>"
html += "<div class=\"myc-card-subtitle\">" + subtitle+ "</div>";
html += "<input type=\"button\" " + "style=\"background-color:rgb(221, 153, 51);text-transform: none\"" + "class=\"myc-quick-reply\" value=\"" +buttons[0]+ "\" />";
var innerHTML = "<div class=\"myc-conversation-bubble-container myc-conversation-bubble-container-response\"><div class=\"myc-conversation-bubble myc-conversation-response myc-is-active myc-quick-replies-response\">" + html + "</div>";
I am getting the image ,title ,subtitle correctly but the Button is displayed as [object Object] what is the correct way to do it?
The button text is in the text property.
Try to replace buttons[0] with buttons[0].text.
in your case buttons is an array of object and have property text. so try buttons[0].text
Related
Question:
I have successfully created a select2 template with a group but I can't select the items in it, is there anything missing from the code I made below? Any help from you means a lot to me, thank you
See this first,
Preview Image
For the data below, i folow https://select2.org/data-sources/formats
Result from AJAX :
{
"status": true,
"message": null,
"data": [
{
"text": "Bank",
"children": [
{
"id": "002",
"icon": ".../payment/bri_1.png",
"text": "BANK BRI"
},
{
"id": "008",
"icon": ".../payment/mandiri_1.png",
"text": "BANK MANDIRI"
},
{
"id": "009",
"icon": ".../payment/bni_1.png",
"text": "BANK BNI / SYARIAH"
},
{
"id": "014",
"icon": ".../payment/bca_1.png",
"text": "BANK BCA"
},
{
"id": "022",
"icon": ".../payment/1280px-CIMB_Niaga_logo.svg.png",
"text": "CIMB NIAGA / SYARIAH"
},
{
"id": "016",
"icon": ".../payment/Maybank-Logo.png",
"text": "Maybank"
},
{
"id": "013",
"icon": ".../payment/images.png",
"text": "PERMATA BANK"
},
{
"id": "213",
"icon": ".../payment/Jenius-logo.png",
"text": "Jenius/BTPN"
},
{
"id": "011",
"icon": ".../payment/kissclipart-danamon-logo-png-clipart-bank-danamon-logo-a9b2b21755c37a3a.png",
"text": "Danamon"
},
{
"id": "012",
"icon": ".../payment/images_1.png",
"text": "Bank Neo Commerce/Bank Yudha Bakti"
},
{
"id": "017",
"icon": ".../payment/images-removebg-preview.png",
"text": "Bank Syariah Indonesia"
}
]
},
{
"text": "eMoney",
"children": [
{
"id": "900",
"icon": ".../payment/ovo.png",
"text": "OVO"
},
{
"id": "901",
"icon": ".../payment/gopay.png",
"text": "GOPAY"
},
{
"id": "903",
"icon": ".../payment/dana_1.png",
"text": "DANA"
},
{
"id": "904",
"icon": ".../payment/linkaja.png",
"text": "LINK AJA"
},
{
"id": "906",
"icon": ".../payment/shopeepay-shopee.co.id_ratio-16x9.jpg",
"text": "SHOPEE PAY"
}
]
}
]
}
Code :
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
minimumResultsForSearch: Infinity,
templateResult: function formatState(state) {
if (!state.id) return state.text;
var $state = $(
'<span><img src="' + state.icon + '" style="width:30px;"/> ' + state.text + '</span>'
);
return $state;
},
ajax: {
url: base_url + 'user/api/payment',
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data.data, function(item, key) {
var children = [];
for (var k in item.children) {
var childItem = [];
childItem.id = item.children[k].id;
childItem.icon = item.children[k].icon;
childItem.text = item.children[k].text;
children.push(childItem);
}
return {
text: item.text,
children: children,
}
})
};
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Payment</label>
<div class="col-sm-10">
<select name="payment" id="payment" class="form-control">
</select>
</div>
</div>
As far as I can see in your code, your API is returning results already formatted, so keep it simple. Please check this fiddle with a fully working example based on your code.
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
ajax: {
url: 'https://randomuser.me/api/', //a random URL to simulate a request response in jsfiddle
dataType: 'json',
processResults: (data) => ({ results: response.data })
}
});
AJAX:
{
"data": [
{
"id": 1,
"name": "Dashboard",
"url": "/",
"icon": "icon-home",
"child_of": null,
"show": 1,
"admin": 0
},
{
"id": 2,
"name": "Submenu 3",
"url": "http://stackoverflow.com",
"icon": null,
"child_of": null,
"show": 1,
"admin": 0
},
]
}
JS:
$('#table-editable').dataTable({
"ajax": {
"url": "/api/menu",
"type": "GET",
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "url" },
{ "data": "icon" },
{ "data": "child_of" },
{ "data": "show" },
{ "data": "admin" }
]
});
So I'm using AJAX to fill up data in tables. It is working.
I am using this: DataTables: Inline Editing for creating new row. (Check Adding row & Edit Mode in link)
Problem:
Consider I've 13 rows. So IDs will be 1, 2, 3... 13.
While creating new row:
It does this: oTable.fnAddData('', '',....);
So when I add new row, it gives me error:
DataTables warning: table id=table-editable - Requested unknown parameter 'id' for row 14. For more information about this error, please see datatables.net/tn/4
So, basically it tries to fetch row id 14. But, there's no row with id 14.
So what is the solution?
var data = [
{
"CategoryID": 1,
"CategoryName": "Soler Power Plant",
"CategoryProducts": [
{
"ID": 1,
"Name": 'Commercial Solar Power Plant',
"SubTitle": 'Eco, Eco Friendly, Energy, Green, Solar',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'Having a pre-determined quality administration system, we are thoroughly involved in delivering Commercial Solar Power Plant.',
"ImageUrl": 'assets/images/Products/Sola-power-plant.jpg',
},
{
"ID": 2,
"Name": 'Industrial Solar Power Plants',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'So as to become a preferential business name, we are thoroughly engrossed in shipping an inclusive collection of Industrial Solar Power Plants.',
"ImageUrl": 'assets/images/Products/Industrial_Solar_Power_Plants.jpg',
},
{
"ID": 3,
"Name": 'On Grid Solar Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 1.1 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Plant.jpg',
},
{
"ID": 4,
"Name": 'On Grid Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Power Plant. To sustain the quality, our products are made under the guidance of industry top professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Power_Plant.jpg',
},
{
"ID": 5,
"Name": 'Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of Solar Power Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/Solar_Power_Plant.jpg',
},
]
}
]
function GetProducts() {
var products = data;
$.each(products, function () {
//var product = products.filter(filterByID)
var product = this;
$('#ProductDetails').append('<h2 class="text-center">' + this.CategoryName + '</h2>');
var details = product;
$.each(details.CategoryProducts, function () {
tempData = tempData + '<div class="col-md-4 col-sm-6">' +
'<div class="project-box">' +
'<div class="frame-outer">' +
'<div class="frame">' +
'<img style="width:350px;" src="' + this.ImageUrl + '" class="attachment-340x220 size-340x220 wp-post-image" alt="">' +
'</div>' +
'</div>' +
'<div class="text-box">' +
'<h3><a>' + this.Name + '</a></h3>' +
'<div class="tags-row">' +
'<a class="link">' + this.SubTitle + '</a>' +
'</div>' +
'<p>' + this.Description + '</p>' +
//'More Details' +
'</div>' +
'</div>' +
'</div>';
});
$('#ProductDetails').append('<div class="row">' + tempData + '</div>');
tempData = '';
});
}
Here, it's my own code may be it's help you
I need to extract JSON string (which will be used later to parse JSON) from a log file. The file is in this format:
[16:11:20] some text
[16:11:20] some text
some text
some text
[
{
"description": "some text",
"elements": [{
"id": "some text",
"keyword": "some text",
"line": 20,
"name": "some text",
"steps": [{
"arguments": [],
"keyword": "some text ",
"result": {
"status": "passed",
"duration": 14884761888
},
"hidden": true,
"match": {
"location": "some text"
}
},
{
"arguments": [],
"keyword": "sometext ",
"name": "sometext",
"result": {
"status": "passed",
"duration": 463674
},
"line": 11,
"match": {
"location": "sometext"
}
}
],
"tags": [
{
"name": "#sometext-no",
"line": 7
},
{
"name": "#sometext",
"line": 8
}
],
"type": "sometext"
}
],
"id": "sometext",
"keyword": "sometext",
"line": 1,
"name": "sometext",
"tags": [],
"uri": "sometext"
}
][16:11:54] some text
[16:11:54] some text
How can I construct a regex in JavaScript which will extract JSON data from this file so that it can be used by string.match() to give the desired output
The pattern I am trying is as below
var regExtract = /(\[\s+\{[\s\S]*\}\s+\]\s+\}\s+\]\s+\}\s+\])/;
var matchedJson = data.toString().match(regExtract)[1];
I update my answer, you can try something like that:
var str = `[16:11:20] some text
[16:11:20] some text
some text
some text
[
{
"description": "some text",
"elements": [{
"id": "some text",
"keyword": "some text",
"line": 20,
"name": "some text",
"steps": [{
"arguments": [],
"keyword": "some text ",
"result": {
"status": "passed",
"duration": 14884761888
},
"hidden": true,
"match": {
"location": "some text"
}
},
{
"arguments": [],
"keyword": "sometext ",
"name": "sometext",
"result": {
"status": "passed",
"duration": 463674
},
"line": 11,
"match": {
"location": "sometext"
}
}
],
"tags": [
{
"name": "#sometext-no",
"line": 7
},
{
"name": "#sometext",
"line": 8
}
],
"type": "sometext"
}
],
"id": "sometext",
"keyword": "sometext",
"line": 1,
"name": "sometext",
"tags": [],
"uri": "sometext"
}
][16:11:54] some text
[16:11:54] some text
`;
var json = '';
var jsonArray = [];
var implode = false;
str.split('\n').forEach(function(v, k){
if(v === ' {'){
console.log(k, v);
implode = true;
}
if(implode){
json = json + v + '\n';
}
if(v === ' }'){
console.log(k, v);
implode = false;
jsonArray.push(json.trim());
json = '';
console.log(jsonArray);
}
});
console.log(JSON.parse(jsonArray[0]));
Fiddle: https://jsfiddle.net/x0cc25q4/7/
UPDATE: Short version with regex:
var arr = str.split('\n').join('').match(/\[\s{2}(\{.*?\})\]/g);
console.log(JSON.parse(arr[0]));
Fiddle: https://jsfiddle.net/x0cc25q4/8/
not sure this works with regexp only since you need to count opening and closing brackets. try
var start=string.indexOf('[{');
var level=1;
start++;
while (level>0){
if (string[start]==='[') level++;
if (string[start]===']') level--;
start++;
}
this surely gets more complicated if there could be '[' or ']' within strings in the json.
Hi this is my JsonObject i want to iterate this and get the values of title elements class of header , Container and footer.
var jsonObj = [{
"Header": {
"title": "Header",
"element":"div",
"class": "innerElements header",
"id": "",
"contenteditable":"true"
},
"Container": {
"title": "Container",
"element": "div",
"class": "innerElements header",
"id": "",
"contenteditable":"true"
},
"Footer": {
"title": "Container",
"element": "div",
"class": "innerElements header",
"id": "",
"contenteditable": "true"
}
}]
You can do this by
for (var key in jsonObj[0]) {
if (jsonObj[0].hasOwnProperty(key)) {
console.log(key + " -> " + jsonObj[0][key].title);
}
}
Here id the fiddle for this code.
For getting the inner elements from the object we have to extend the previous loop
for (var key in jsonObj[0]) {
if (jsonObj[0].hasOwnProperty(key)) {
console.log(key + " ---");
for(innerKey in jsonObj[0][key]) {
console.log(innerKey + " -> " + jsonObj[0][key][innerKey])
}
console.log("-----")
}
}
Here is the fiddle for above code
Im trying to modify script from https://github.com/bigflannel/bigflannel-Instafeed to access Instagram Photos in Website. But it doesn't include feature to display photo comments. So, im trying to modify but it returns undefined value. The script uses javascript to access data from API.
Example:
[
{
"attribution": null,
"tags": [
],
"type": "image",
"location": null,
"comments": {
"count": 2,
"data": [
{
"created_time": "1389168592",
"text": "Beautiful bridge!",
"from": {
"username": "realwahyuputra",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
"id": "180213154",
"full_name": "realwahyuputra"
},
"id": "628714182443349004"
},
{
"created_time": "1389168601",
"text": "also good views",
"from": {
"username": "realwahyuputra",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
"id": "180213154",
"full_name": "realwahyuputra"
},
"id": "628714254652486672"
}
]
},
"filter": "Hefe",
"created_time": "1350749506",
"link": "http:\/\/instagram.com\/p\/RAqdlGyTSc\/",
"likes": {
"count": 0,
"data": [
]
},
"images": {
"low_resolution": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [
],
"caption": {
"created_time": "1350749545",
"text": "From the office",
"from": {
"username": "bigflannel",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
"id": "240129684",
"full_name": "Mike Hartley"
},
"id": "306431853609956969"
},
"user_has_liked": false,
"id": "306431525321782428_240129684",
"user": {
"username": "bigflannel",
"website": "",
"profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
"full_name": "Mike Hartley",
"bio": "",
"id": "240129684"
}
}];
Here's one of function to access data from that JSON:
function imageCaptionText(timestamp) {
var text = 'Filter: ' + imageData[imageCount].filter + '<br />'
if (imageData[imageCount].caption != null) {
text = text + 'Caption: ' + imageData[imageCount].caption.text + '<br />';
}
if (imageData[imageCount].likes.count > 0) {
text = text + 'Likes: ' + imageData[imageCount].likes.count + '<br />';
}
if (imageData[imageCount].comments.count > 0) {
text = text + 'Comments: ' + imageData[imageCount].comments.count + '<br />';
}
if (imageData[imageCount].comments.data != null) {
text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
if (imageData[imageCount].location != null) {
text = text + 'Location: ' + imageData[imageCount].location + '<br />';
}
var date = new Date(1000*timestamp);
text = text + 'Date: ' + date.toLocaleString() + '<br />';
text = text + 'On Instagram<br />';
return text; }
Everything goes fine except this code returns undefined value (I'm trying to create this to access comments data)
if (imageData[imageCount].comments.data != null) {
text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
How to make it works? Any help would be appreciated. Thanks :)
comments.data is an array, the actual text will be at imageData[imageCount].comments.data[commentCount].text so you have to do something like this:
if (imageData[imageCount].comments.data != null) {
text = 'Comments Data:<br />';
imageData[imageCount].comments.data.forEach(function(comment){
text += comment.from.username + ': ' + comment.text + '<br />';
});
}