I have a JSON response and I am trying to get autocomplete to work but it is having issues.
Question:
Here is my jQuery ajax "success" method to handle the returned JSON string: (I have listed my JSON response below):
The Code:
success: function( data ) {
response( $.map( data.productSkus, function( item ) {
return {
label: item.product.name + " - " + item.product.sku,
name: item.product.name,
value: item.product.sku,
id: item.product.id,
product_sku: item.product.sku
}
}));
}
The Issue:
I am sure that the issue why it isn't showing options is because each array element has the "0": { before the content of the array. How do I access these? I have tried item[0] but that does not seem to work. I know that this script works, it just broke when I had to do a "group by" in my php code. Once I did the group by it added the "0": {. Thanks for your help!
JSON Response:
{
"responseCode": 200,
"responseVal": "Success",
"productSkus": [
{
"0": {
"id": 16685,
"qty": 8,
"reserved_qty": 0,
"created": {
"date": "2014-01-20 17:32:31",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"inventoryLocation": {
"id": 523,
"saleable": true,
"name": "M-10A-4",
"created": {
"date": "2013-04-11 18:46:11",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": {
"date": "2013-04-11 18:46:11",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"deletedAt": null,
"warehouse": {
}
}
},
"name": "Tiger Costume Brown"
},
{
"0": {
"id": 48917,
"qty": 0,
"reserved_qty": 0,
"created": {
"date": "2014-01-20 23:44:15",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"inventoryLocation": {
"id": 4056,
"saleable": true,
"name": "W-2E-26R-204",
"created": {
"date": "2014-01-20 23:30:58",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"warehouse": {
}
}
},
"name": "Tiger Costume White"
}
],
"productsCount": 7
}
I would doublecheck this on the phpside and maybe correct it (just take the element under zero and append it directly). If this isnt possible correct it in JS:
success: function( data ) {
response( $.map( data.productSkus, function( item ) {
if(item[0]){
item[0].name = item.name
item = item[0];
}
return {
label: item.name + " - " + item.sku,
name: item.name,
value: item.sku, // Not in the JSON
id: item.id,
product_sku: item.sku // Not in the JSON
}
}));
}
When this isnt working, use typeof instead.
// Edit: Did crap. Corrected it
// Edit: Removed the product-key since it is not present in the JSON
// Edit: Now it nearly fits the json
My issue was actually in my PHP code. Disregard this question all together.
Related
I have a JSON object which has multiple children and grandchildren I want to get the sum of grandchildren and show it with the children, similar get the sum of children and show it with the parent.
So in the end, the parent should display the sum of all children.
{
"id": 4,
"Nominal": "4",
"name": "Revenue",
"type": "Revenue",
"parent_id": 0,
"children": [
{
"id": 14,
"Nominal": "41",
"name": "Operational Revenue",
"parent_id": 4,
"transactions_sum_debit": null,
"transactions_sum_credit": null,
"children": [
{
"id": 46,
"Nominal": "4101",
"name": "Revenue of Products and services Sales",
"parent_id": 41,
"transactions_sum_debit": "1658.00",
"transactions_sum_credit": "3316.00",
"children": [],
"transactions": [
{
"id": 308,
"debit": null,
"credit": "64.00",
"first_level_id": 46
},
{
"id": 310,
"debit": null,
"credit": "765.00"
},
{
"id": 318,
"debit": null,
"credit": "64.00",
"first_level_id": 46,
"invoice_id": 20
},
{
"id": 320,
"debit": null,
"credit": "765.00",
"first_level_id": 46
},
{
"id": 340,
"debit": null,
"credit": "765.00",
"first_level_id": 46
},
{
"id": 466,
"debit": "64.00",
"credit": null,
"first_level_id": 46
},
{
"id": 468,
"debit": "765.00",
"credit": null,
"first_level_id": 46
}
]
}
],
"transactions": []
},
{
"id": 15,
"Nominal": "42",
"parent_id": 4,
"transactions_sum_debit": null,
"transactions_sum_credit": null,
"children": [
{
"id": 47,
"Nominal": "4201",
"parent_id": 42,
"transactions_sum_debit": null,
"transactions_sum_credit": "1520.00",
"children": [],
"transactions": [
{
"id": 304,
"debit": null,
"credit": "380.00",
"first_level_id": 47
},
{
"id": 334,
"debit": null,
"credit": "380.00",
"first_level_id": 47
}
]
}
],
"transactions": []
}
]
}
for example in the above JSON data I want to get the sum transactions_sum_debit from all the children and show it one level up. until the parent_id = 0
My View:
//get sum of all children in json
function sumOfChildrens(parent, id) {
let data = parent;
let ids = id;
let transactions_sum_credit = 0;
//call the function recursively until the last child
for (let i = 0; i < data.length; i++) {
if (data[i].id == ids) {
transactions_sum_credit += parseFloat(data[i].transactions_sum_credit);
}
if (data[i].children) {
transactions_sum_credit += sumOfChildrens(data[i].children, ids);
}
}
console.log(transactions_sum_credit);
return transactions_sum_credit;
}
$(document).ready(function() {
$.ajax({
headers: {
"Authorization": 'Bearer ' + sessionStorage.getItem('token')
},
type: "get",
url: "{{ URL::asset('api/reports/get-generalLedger') }}",
success: function(data) {
var data = data.data;
console.log(data);
$("#tablebody").empty();
data.map(parent => {
$("#tablebody").append(
`
<tr>
<td class="${parent.Nominal} id_${parent.id}">${parent.Nominal}</td>
<td class="${parent.Nominal} id_${parent.id}">${parent.name}</td>
<td class="${parent.Nominal} id_${parent.id}"></td>
<td class="${parent.Nominal} id_${parent.id}">${sumOfChildrens(parent,parent.id)}</td>
</tr>
`);
});
},
error: function(data) {
alert(data['message']);
console.log(data['message']);
},
});
});
Stackoverflow isn't meant for other people to write code for you, but rather to answer specific questions or help solve problems. Instead of showing more code, explain what you've tried, which behavior you saw vs the one you expected.
That being said, I think the following code snippet might help you clarify your question or even solve the problem on your own.
// for each first level child
data.children.map((item) => {
// for each next level child
item.children.map((item2) => {
// this is the list of transactions
console.log(item2.transactions);
let sum = 0;
// go over each transaction
item2.transactions.map((transaction) => {
// debit != null
if (transaction.debit) {
sum += parseFloat(transaction.debit);
}
});
// here you could add the sum to the parent
console.log(sum);
});
});
Try to edit this code so it works for you and come back if you have more questions.
here is the code ,i just want to grab "url" key and its value and store it in a variable
i have tried several ways to segregate the key named url you can see that in my commented code
$.ajax({
type: 'GET',
url: "url",
// data: data,
// async: false,
beforeSend: function(xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function(res) {
// console.log(res);
// re=JSON.stringify(res);
re = $.parseJSON(res)
console.log(re['url'])
// console.log(re)
// console.log(re["url"])
// for(var url in re) {
// var value = objects[key];
// }
// console.log(Object.values('url'));
// ok=Object.keys(re).map(key => re[url])
// console.log(ok)
// console.log(re)
// $.each(re, function(key, value){
// console.log(key + value);
// });
// console.log(re[url])
// const seg = re.find(item => item.key === "url");
// const result=seg
// console.log(result)
// alert(res);
}
});
You need to resolve CORS issues with your Django backend to get the response correctly.
I see the response is of the following structure:
{
"count": 51,
"next": "http://scrapsh.herokuapp.com/api/post/?page=2",
"previous": null,
"results": [
{
"id": 1,
"title": "asdas",
"rate": 1,
"author": "madhumani",
"content": "asdad",
"review": null,
"url": null
},
{
"id": 2,
"title": "okau",
"rate": 1,
"author": "madhumani",
"content": "asdasd",
"review": null,
"url": null
},
{
"id": 3,
"title": "DASS",
"rate": 1,
"author": "madhumani",
"content": "sdfsdfs",
"review": null,
"url": null
},
...
]
}
To get the url you can simply use .map on the results array:
let response = {
"count": 51,
"next": "http://scrapsh.herokuapp.com/api/post/?page=2",
"previous": null,
"results": [{
"id": 1,
"title": "asdas",
"rate": 1,
"author": "madhumani",
"content": "asdad",
"review": null,
"url": "www.a.com"
},
{
"id": 2,
"title": "okau",
"rate": 1,
"author": "madhumani",
"content": "asdasd",
"review": null,
"url": "www.b.com"
},
{
"id": 3,
"title": "DASS",
"rate": 1,
"author": "madhumani",
"content": "sdfsdfs",
"review": null,
"url": "www.c.com"
}
]
}
console.log(response.results.map(item => {
return {
"url": item.url
}
}))
I am trying to access an object (tmp_name) within a Woocommerce webhook payload in AWS Lambda. At the moment I can output the "line item" with:
exports.handler = (event, context, callback, err) => {
callback(null, event.line_items);
if (err) console.log('JSON Pass Fail'); // an error occurred
else console.log(event.order_key); // successful response
};
When I try to go deeper into the event data it runs as null, such as
callback(null,event.line_items.meta_data.value.tmp_name);
I have tried accessing the array with 0 and [0] with no joy either.
Eventually if I can access the file path, i need to strip out the backslahes so it looks like a proper file path. I have got the regex for that which is string.replace(/\\\//g, "/");
Can anyone help me put this together?
{
"line_items": [
{
"id": 2,
"name": "Audio 5",
"product_id": 15,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "10.00",
"subtotal_tax": "0.00",
"total": "10.00",
"total_tax": "0.00",
"taxes": [
],
"meta_data": [
{
"id": 20,
"key": "_wcj_product_input_fields_global_1",
"value": {
"name": "Aaron Ramsey's departure from Arsenal to Juventus.mp3",
"type": "audio\/mp3",
"tmp_name": "\/home\/site\/public_html\/wp-content\/uploads\/woocommerce_uploads\/wcj_uploads\/input_fields_uploads\/21.mp3",
"error": 0,
"size": 4943085,
"wcj_type": "file"
}
}
],
"sku": "",
"price": 10
}
],
"tax_lines": [
],
"shipping_lines": [
],
"fee_lines": [
],
"coupon_lines": [
],
"refunds": [
]
}
I am creating a Tableau Web Data Connector as per the documentation HERE.
I am running the Simulator and have setup a HTML page (as per tutorial) which calls a Javascript file that runs the Tableau WDC script as below.
(function () {
var myConnector = tableau.makeConnector();
myConnector.init = function(initCallback) {
initCallback();
tableau.submit();
};
myConnector.getSchema = function (schemaCallback) {
var cols = [
{ id : "date_of_work", alias : "Date of Work", dataType: tableau.dataTypeEnum.date },
{ id : "supervisor", alias : "Supervisor", dataType: tableau.dataTypeEnum.string }
];
var tableInfo = {
id : "test",
alias : "test",
columns : cols
};
schemaCallback([tableInfo]);
};
myConnector.getData = function (table, doneCallback) {
$.getJSON("http://myDataCall.php", function(response) {
// ERROR HERE!
var resp = response.job.job_workflows; // Response
var parsedResp = JSON.parse(resp); // Parse the response
var tableData = []; // Temp array
// Iterate over the JSON object
for (var i = 0, len = resp.length; i < len; i++) {
tableData.push({
"date_of_work": parsedResp[i]['job_status'],
"supervisor": parsedResp[i]['job_workflow_1197927'],
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
})();
When I run the script I get the error: The WDC reported an error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1 stack:SyntaxError:
Unexpected token o in JSON at position 1 at JSON.parse () at Object.success
The (abbreviated) JSON that is being returned looks as follows:
{
"employee": {
"id": 23940,
},
"company": {
"id": 1059,
},
"job": {
"id": 13712707,
"job_status_logs": [{
"id": 17330391,
}],
"company": {
"id": 1059,
},
"created_by": {
"id": 23940,
},
"job_workflows": [{
"id": 1087689283,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251218,
"name": "Date of work",
"action": "datepicker",
"optional": 0,
"action_values": "",
"action_value_entered": "2017-10-12",
"nested_workflow_id": 0,
}, {
"id": 1087689284,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251219,
"name": "Supervisor",
"action": "list",
"optional": 0,
"action_values": "John Doe",
"action_value_entered": "John Doe",
"nested_workflow_id": 0,
}],
"job_fields": [{
"id": 50456098,
}],
"job_status_change_messages": [{
"id": 59957985}],
"job_assets":[]
}
}
I am trying to access the job.job_workflows.action_value_entered value but keep getting the error as above.
How can I fix this error?
There are a couple of issues here.
1) The JSON sent back from your server is invalid. Here is the valid version. I recommend using a site like https://jsonformatter.curiousconcept.com/ to validate your JSON.
{
"employee": {
"id": 23940
},
"company": {
"id": 1059
},
"job": {
"id": 13712707,
"job_status_logs": [{
"id": 17330391
}],
"company": {
"id": 1059
},
"created_by": {
"id": 23940
},
"job_workflows": [{
"id": 1087689283,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251218,
"name": "Date of work",
"action": "datepicker",
"optional": 0,
"action_values": "",
"action_value_entered": "2017-10-12",
"nested_workflow_id": 0
}, {
"id": 1087689284,
"job_id": 13712707,
"employee_id": null,
"template_workflow_id": 1251219,
"name": "Supervisor",
"action": "list",
"optional": 0,
"action_values": "John Doe",
"action_value_entered": "John Doe",
"nested_workflow_id": 0
}],
"job_fields": [{
"id": 50456098
}],
"job_status_change_messages": [{
"id": 59957985}],
"job_assets":[]
}
}
2) jQuery's getJson method returns an object, so you don't need to parse it. You can just use the resp variable directly like so:
var resp = response.job.job_workflows; // Response
var tableData = []; // Temp array
// Iterate over the JSON object
for (var i = 0, len = resp.length; i < len; i++) {
tableData.push({
"date_of_work": resp[i]['job_status'],
"supervisor": resp[i]['job_workflow_1197927'],
});
}
table.appendRows(tableData);
doneCallback();
Fixing those two issues should unblock you. However, you'll want to think through what data you are sending back. The current values you are sending back do not exist in the JSON (i.e. resp[i]['job_workflow_1197927']).
Instead, you could do something like this: resp[1].job_id, which would give you the job_id of each job_workflow.
I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data