I'm fairly new to YUI and facing an issue while trying to create a YUI3 DataTable from the below JSON -
{
"generations": [
{
"type": "Modern",
"showName": "The Modern Generation",
"imgURI": "file:/D:/projectGen.png",
"relations": {
"father": {
"age": "49",
"firstName": "George",
"lastName": "Mathews",
"priority": "1",
"profession": "Service"
},
"mother": {
"age": "47",
"firstName": "Susan",
"lastName": "Aldrin",
"priority": "2",
"profession": "Home-Maker"
},
"brother": {
"age": "28",
"firstName": "Martin",
"lastName": "Mathews J",
"priority": "3",
"profession": "Engineer"
},
"sister": {
"age": "23",
"firstName": "Laura",
"lastName": "Mathews J",
"priority": "4",
"profession": "Fashion Model"
}
}
}
]
}
The table which I need to create should look like the one below -
Any info on how can I do this?
A JSFiddle would be appreciated.
I hope this helps. http://jsfiddle.net/BM3kX/2/
HTML:
<div class="yui3-skin-sam" id="datatable"></div>
Javascript:
YUI().use('datatable', 'datasource-local', 'datasource-jsonschema',function(Y){
var data = {};//JSON here
var localDataSource = new Y.DataSource.Local({source:data});
localDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: 'generations',
resultFields: [{key:'showName'},
{
key:'father',
locator:'relations.father.firstName'
},
{
key:'mother',
locator:'relations.mother.firstName'
},
{
key:'brother',
locator:'relations.brother.firstName'},
{
key:'sister',
locator:'relations.sister.firstName'
}]
}
});
var table = new Y.DataTable({
columns: ["showName", "father","mother","brother","sister"]
});
table.plug(Y.Plugin.DataTableDataSource, {
datasource: localDataSource
});
table.render('#datatable');
table.datasource.load();
});
Related
Here i have got array of objects data, from this data i need to delete the element based on a value, if value is found then delete entire element
let value = "/unifiedconfig/config/agent/5197";
//if this found in json data i have delete complete element{"refURL":"/unifiedconfig/config/agent/5197","agentId":"1085","firstName":"Owen","lastName":"Harvey","userName":"oharvey"}
var myjsonobj = {
"refURL": "/unifiedconfig/config/agentteam/5022",
"changeStamp": 12,
"agentCount": 7,
"description": "Cumulus Outbound Team",
"name": "CumulusOutbound",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [{
"agent": [{
"refURL": "/unifiedconfig/config/agent/5197",
"agentId": "1085",
"firstName": "Owen",
"lastName": "Harvey",
"userName": "oharvey"
}, {
"refURL": "/unifiedconfig/config/agent/5201",
"agentId": "1320",
"firstName": "Bruce",
"lastName": "Wayne",
"userName": "bwayne"
}, {
"refURL": "/unifiedconfig/config/agent/5202",
"agentId": "1321",
"firstName": "Peter",
"lastName": "Parker",
"userName": "pparker"
}, {
"refURL": "/unifiedconfig/config/agent/5203",
"agentId": "1322",
"firstName": "Tony",
"lastName": "Stark",
"userName": "tstark"
}, {
"refURL": "/unifiedconfig/config/agent/5204",
"agentId": "1323",
"firstName": "Steve",
"lastName": "Rogers",
"userName": "srogers"
}, {
"refURL": "/unifiedconfig/config/agent/5205",
"agentId": "1324",
"firstName": "Bruce",
"lastName": "Banner",
"userName": "bbanner"
}, {
"refURL": "/unifiedconfig/config/agent/5231",
"agentId": "1086",
"firstName": "Annika",
"lastName": "Hamilton",
"userName": "annika"
}, {
"refURL": "/unifiedconfig/config/agent/5118",
"agentId": "1317",
"firstName": "Donald",
"lastName": "Duckling",
"userName": "dduck"
}]
}],
"supervisors": [{
"supervisor": [{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}]
}]
}
Object.keys(myjsonobj).forEach(function(key) {
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(JSON.stringify(myjsonobj));
This should do the trick:
var myjsonobj = {"refURL": "/unifiedconfig/config/agentteam/5022","changeStamp": 12,"agentCount": 7,"description": "Cumulus Outbound Team","name": "CumulusOutbound","peripheral": {"id": 5000,"name": "CUCM_PG_1"},"peripheralId": 5000,"supervisorCount": 1,"agents": [{"agent": [{"refURL": "/unifiedconfig/config/agent/5197","agentId": "1085","firstName": "Owen","lastName": "Harvey","userName": "oharvey"}, {"refURL": "/unifiedconfig/config/agent/5201","agentId": "1320","firstName": "Bruce","lastName": "Wayne","userName": "bwayne"}, {"refURL": "/unifiedconfig/config/agent/5202","agentId": "1321","firstName": "Peter","lastName": "Parker","userName": "pparker"}, {"refURL": "/unifiedconfig/config/agent/5203","agentId": "1322","firstName": "Tony","lastName": "Stark","userName": "tstark"}, {"refURL": "/unifiedconfig/config/agent/5204","agentId": "1323","firstName": "Steve","lastName": "Rogers","userName": "srogers"}, {"refURL": "/unifiedconfig/config/agent/5205","agentId": "1324","firstName": "Bruce","lastName": "Banner","userName": "bbanner"}, {"refURL": "/unifiedconfig/config/agent/5231","agentId": "1086","firstName": "Annika","lastName": "Hamilton","userName": "annika"}, {"refURL": "/unifiedconfig/config/agent/5118","agentId": "1317","firstName": "Donald","lastName": "Duckling","userName": "dduck"}]}],"supervisors": [{"supervisor": [{"refURL": "/unifiedconfig/config/agent/5174","agentId": "1082","firstName": "Rick","lastName": "Barrows","userName": "rbarrows#dcloud.cisco.com"}]}]}
let value = "/unifiedconfig/config/agent/5197";
myjsonobj.agents[0].agent=myjsonobj.agents[0].agent.filter(a=>a.refURL!=value);
console.log(myjsonobj)
From your data it looks pretty obvious that the target value can only be found in the refURL property of the agent-elements. So this is what I focused on in the above script.
this is my json code that returns an array "Customers" that contains objects and arrays inside objets
This is my json cod:
{
"Customers": [
{
"customerData": {
"secondLastName": "Apale",
"firstLastName": "Lara",
"phoneNumber": "2711292033",
"address": "Calle X avenida Y #100",
"paymentCapacity": 18000,
"gender": "Femenino",
"name": "Yessica",
},
"orders": [
{
"amount": 34371,
"term": "2017-07-21T17:32:28Z",
"payment": 1423,
"id": 12345678,
"calculationDate": "2017-07-21T17:32:28Z",
"products": [
{
"SKUNumber": 28005417,
"quantity": 1,
"SKULineDescription": "Computadoras",
"SKUDescription": "Laptop HP",
"SKULineId": 4
}
]
}
]
},
{
"customerData": {
"secondLastName": "González",
"firstLastName": "Pineda",
"phoneNumber": "55678420",
"address": "Calle 26 #4732 Col. Pradera",
"paymentCapacity": 180,
"gender": "Femenino",
"name": "María",
},
"orders": [
{
"amount": 34371,
"term": "2017-07-21T17:32:28Z",
"payment": 1423,
"id": 12678422,
"calculationDate": "2017-07-21T17:32:28Z",
"products": [
{
"SKUNumber": 28005417,
"quantity": 1,
"SKULineDescription": "Computadoras",
"SKUDescription": "Laptop HP",
"SKULineId": 4
}
]
}
]
}
]
}
this is the declaration og my array: arrCustomers = new Array();
I try to loop through the json with foreach and i have error that says: undefined, this is my console
I guess you were having trouble accessing elements of array and objects. If it is the case then may this help you.
Also, run those snippets who are commented.
You may access objects attribute in 2 ways, one is using dot(.) operator and another one is used in the example.
var array = {
"Customers": [
{
"customerData": {
"secondLastName": "Apale",
"firstLastName": "Lara",
"phoneNumber": "2711292033",
"address": "Calle X avenida Y #100",
"paymentCapacity": 18000,
"gender": "Femenino",
"name": "Yessica",
},
"orders": [
{
"amount": 34371,
"term": "2017-07-21T17:32:28Z",
"payment": 1423,
"id": 12345678,
"calculationDate": "2017-07-21T17:32:28Z",
"products": [
{
"SKUNumber": 28005417,
"quantity": 1,
"SKULineDescription": "Computadoras",
"SKUDescription": "Laptop HP",
"SKULineId": 4
}
]
}
]
},
{
"customerData": {
"secondLastName": "González",
"firstLastName": "Pineda",
"phoneNumber": "55678420",
"address": "Calle 26 #4732 Col. Pradera",
"paymentCapacity": 180,
"gender": "Femenino",
"name": "María",
},
"orders": [
{
"amount": 34371,
"term": "2017-07-21T17:32:28Z",
"payment": 1423,
"id": 12678422,
"calculationDate": "2017-07-21T17:32:28Z",
"products": [
{
"SKUNumber": 28005417,
"quantity": 1,
"SKULineDescription": "Computadoras",
"SKUDescription": "Laptop HP",
"SKULineId": 4
}
]
}
]
}
]
}
console.log("the whole array ==>",array);
//console.log("customers attribute ==>",array["Customers"]);
//console.log("first customerData ==>",array["Customers"][0]);
//console.log("first customerData's order ==>",array["Customers"][0]["orders"]);
//console.log("first customerData's all products ==>",array["Customers"][0]["orders"].map(i => i["products"]));
//console.log("All customerDatas", array["Customers"].map(i => i["customerData"]));
//console.log("All orders", array["Customers"].map(i => i["orders"]));
//console.log("All orders of all customers", array["Customers"].map(i => i["orders"]));
I have the following JSON response coming from an API.
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
Language I'm using to parse this JSON: Javascript
Framework: ReactNative
How do I parse it (NOTE: I don't know the value of id in cakes until I parse it)?
PS: New to the framework. Big thanks.
I am not sure about that but I think you want to somehow access a cake with id e.x. 7689 without knowing its id value. So you have several ways to deal with it. One of them is to iterate over them using for...in loop:
for(var cakeId in response.cakes){
var cake = response.cakes[cakeId];
console.log(cake);
// Do whatever you want with your cake
}
I am sorry if I misunderstood you. If so, please clarify the question by providing us with some examples of what you would like to achieve.
create a function
function getCake(obj,key){
let cake = obj['cakes'][key];
return cake;
}
call
let cakes = {
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
getCake(cakes,'7689');
Try this out
const cakesObject = {
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
};
// this is required only if cakesObject is strigified
const { cakes } = JSON.parse(cakesObject);
const cakesArray = [..Object.values(cakes)];
cakesArray.forEach(cake => {
const { id } = cake;
// write further logic
})
I have a document that resembles:
[
{
"subscriberid": "4355",
"Title": "Miss",
"FirstName": "FirstName",
"LastName": "LastName",
"EmailAddress": "thisisanemail#email.com",
"Mobile": "",
"Postcode": "B1 3qq",
"Gender": "",
"SubscribeDate": "2015-08-12 10:58:29",
"Birthday": "31-5-1985",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "1113111",
"attendreason": "Array",
"MarketingOptIn": "Y",
"Source": "WEBSITE",
"Login": [
{
"subscriberid": "4355",
"Created_at": "2017-05-18 10:09:44",
"IPaddress": "1.1.2.3"
}
]
},
{
"subscriberid": "125",
"Title": "",
"FirstName": "FirstName2",
"LastName": "LastName2",
"EmailAddress": "thisisalsoanemail#email.com",
"Mobile": "",
"Postcode": "tn39 4de",
"Gender": "",
"SubscribeDate": "2015-12-02 17:21:18",
"Birthday": "13-3-1922",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "8108200",
"attendreason": "Date",
"MarketingOptIn": "Y",
"Source": "FACEBOOK",
"Vouchers": [
{
"subscriberid": "213",
"Created_at": "2017-05-18 08:57:47",
"Source": "some website",
"offer": "50offMains",
"name": "50% off Mains"
}
],
"Login": [
{
"subscriberid": "123",
"Created_at": "2017-05-18 07:57:46",
"IPaddress": "1.2.3.4"
}
]
}
]
And I'm trying to turn it into a CSV, automatically. Normally this would be a very simple script with json2csv, but for some reason this time I'm having an issue that I'm struggling to troubleshoot. My file is being created, but with headers only and no data.
I read the docs on https://github.com/zemirco/json2csv and I'm thinking I would use dot notation for the fields but due to how it's setup, I'm unsure what would preceed the dot?
I tried CLI version and an actual JS Version but same deal. All I get is the headers. As you'll see in the script, I only care about parts of the JSON Document, but even if I try to do it all, I still only get the headers. My previous versions have all used glob, but the CLI and pointing directly to the file still nets the same result.
var json2csv = require('json2csv');
var fs = require('fs');
var glob = require('glob');
let fields =
[
"subscriberid",
"Title",
"FirstName",
"LastName",
"EmailAddress",
"Mobile",
"Postcode",
"Gender",
"SubscribeDate",
"Birthday",
"Kids",
"Kidsages",
"Student",
"Favourite",
"attendreason",
"MarketingOptIn",
"Source"
];
let dataInput = glob("path/**/toFile.txt");
var csv = json2csv({ data: dataInput, fields: fields });
fs.writeFile('output.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
I'm trying to loop through all this array data but it won't work out how to display it all via jquery using the .each function? Can someone help me out?
ARRAY:
{
"ListOrdersResult": {
"Orders": {
"Order": [
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
},
{
"ShipmentServiceLevelCategory": "Standard",
"OrderTotal": {
"Amount": "29.00",
"CurrencyCode": "GBP"
},
"ShipServiceLevel": "Std UK Dom",
"LatestShipDate": "2013-11-28T23:59:59Z",
"MarketplaceId": "A1F83G8C2ARO7P",
"SalesChannel": "Amazon.co.uk",
"ShippingAddress": {
"Phone": "0800 000 0000",
"PostalCode": "A11 H11",
"Name": "stephanie ross",
"CountryCode": "GB",
"StateOrRegion": "regiion",
"AddressLine2": "cairnbulg",
"AddressLine1": "loco 2222 name",
"City": "fraserburgh"
},
"ShippedByAmazonTFM": "false",
"OrderType": "StandardOrder",
"FulfillmentChannel": "MFN",
"BuyerEmail": "c9tkdmn724jpgkd#blahblah.com",
"OrderStatus": "Shipped",
"BuyerName": "custom A Ross",
"LastUpdateDate": "2013-11-27T14:26:53Z",
"EarliestShipDate": "2013-11-27T00:00:00Z",
"PurchaseDate": "2013-11-26T22:25:39Z",
"NumberOfItemsUnshipped": "0",
"AmazonOrderId": "205-8108202-4976362",
"NumberOfItemsShipped": "1",
"PaymentMethod": "Other"
}
]
},
"CreatedBefore": "2014-05-14T01:12:05Z"
},
"ResponseMetadata": {
"RequestId": "46f5c980-91e6-44d3-bc9d-668976855862"
},
"xmlns": "https://mws.amazonservices.com/Orders/2011-01-01"
}
CURRENT JS:
$(document).ready(function(){
$.get('functions/ListOrders.php', function(xml){
var newOrders = $.xml2json(xml);
$.each(newOrders.Orders.Order, function(index, value) {
console.log(value);
console.log(value.ShipmentServiceLevelCategory);
});
$('body').text(JSON.stringify(newOrders));
});
});
You are missing the first element of the JSON object:
Change
$.each(newOrders.Orders.Order, function(index, value) {
To
$.each(newOrders.ListOrdersResult.Orders.Order, function(index, value) {
Demo:
http://jsfiddle.net/9YU3H/