I am trying to convert a JSON to CSV with JavaScript. The problem is I keep getting the error: Cannot convert undefined or null to object
at Function.keys.
I only want the 'features.attributes' keys and values from the data. I have no problem getting the keys but the values seems to be a problem. Any help wuld be appreciated.
json
{
"displayFieldName": "label",
"fieldAliases": {
"OBJECTID": "OBJECTID",
"label": "label",
"west": "west",
"east": "east",
"north": "north",
"south": "south",
"scale": "scale",
"title": "title",
"edition": "edition",
"available": "available",
"physHold": "physHold",
"primeMer": "primeMer",
"projection": "projection",
"publisher": "publisher",
"datePub": "datePub",
"color": "color",
"recId": "recId",
"note": "note",
"location": "location",
"bathLines": "bathLines",
"bathInterv": "bathInterv",
"instCallNo": "instCallNo",
"setTitle": "setTitle",
"sheetId": "sheetId",
"digita": "digita",
"titleAlt": "titleAlt",
"digHold": "digHold",
"miradorURL": "miradorURL",
"iiifURL": "iiifURL",
"Shape_Length": "Shape_Length",
"Shape_Area": "Shape_Area"
},
"geometryType": "esriGeometryPolygon",
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
},
"fields": [
{
"name": "OBJECTID",
"type": "esriFieldTypeOID",
"alias": "OBJECTID"
},
{
"name": "label",
"type": "esriFieldTypeString",
"alias": "label",
"length": 50
},
{
"name": "west",
"type": "esriFieldTypeDouble",
"alias": "west"
},
{
"name": "east",
"type": "esriFieldTypeDouble",
"alias": "east"
},
{
"name": "north",
"type": "esriFieldTypeDouble",
"alias": "north"
},
{
"name": "south",
"type": "esriFieldTypeDouble",
"alias": "south"
},
{
"name": "scale",
"type": "esriFieldTypeInteger",
"alias": "scale"
},
{
"name": "title",
"type": "esriFieldTypeString",
"alias": "title",
"length": 55
},
{
"name": "edition",
"type": "esriFieldTypeString",
"alias": "edition",
"length": 85
},
{
"name": "available",
"type": "esriFieldTypeSmallInteger",
"alias": "available"
},
{
"name": "physHold",
"type": "esriFieldTypeString",
"alias": "physHold",
"length": 3
},
{
"name": "primeMer",
"type": "esriFieldTypeSmallInteger",
"alias": "primeMer"
},
{
"name": "projection",
"type": "esriFieldTypeString",
"alias": "projection",
"length": 19
},
{
"name": "publisher",
"type": "esriFieldTypeString",
"alias": "publisher",
"length": 33
},
{
"name": "datePub",
"type": "esriFieldTypeSmallInteger",
"alias": "datePub"
},
{
"name": "color",
"type": "esriFieldTypeSmallInteger",
"alias": "color"
},
{
"name": "recId",
"type": "esriFieldTypeString",
"alias": "recId",
"length": 30
},
{
"name": "note",
"type": "esriFieldTypeString",
"alias": "note",
"length": 254
},
{
"name": "location",
"type": "esriFieldTypeString",
"alias": "location",
"length": 254
},
{
"name": "bathLines",
"type": "esriFieldTypeString",
"alias": "bathLines",
"length": 5
},
{
"name": "bathInterv",
"type": "esriFieldTypeString",
"alias": "bathInterv",
"length": 50
},
{
"name": "instCallNo",
"type": "esriFieldTypeString",
"alias": "instCallNo",
"length": 50
},
{
"name": "setTitle",
"type": "esriFieldTypeString",
"alias": "setTitle",
"length": 50
},
{
"name": "sheetId",
"type": "esriFieldTypeInteger",
"alias": "sheetId"
},
{
"name": "digita",
"type": "esriFieldTypeString",
"alias": "digita",
"length": 8000
},
{
"name": "titleAlt",
"type": "esriFieldTypeString",
"alias": "titleAlt",
"length": 8000
},
{
"name": "digHold",
"type": "esriFieldTypeString",
"alias": "digHold",
"length": 8000
},
{
"name": "miradorURL",
"type": "esriFieldTypeString",
"alias": "miradorURL",
"length": 8000
},
{
"name": "iiifURL",
"type": "esriFieldTypeString",
"alias": "iiifURL",
"length": 8000
},
{
"name": "Shape_Length",
"type": "esriFieldTypeDouble",
"alias": "Shape_Length"
},
{
"name": "Shape_Area",
"type": "esriFieldTypeDouble",
"alias": "Shape_Area"
}
],
"features": [
{
"attributes": {
"OBJECTID": 1,
"label": " ",
"west": -5.8263888899999996,
"east": -5.7838888900000001,
"north": 35.770000000000003,
"south": 35.814166669999999,
"scale": 5000,
"title": "Port de Tanger",
"edition": " ",
"available": 1,
"physHold": "yes",
"primeMer": 131,
"projection": " ",
"publisher": " ",
"datePub": 1908,
"color": 31,
"recId": "agsmap026454",
"note": "\\\\ $a Relief shown by form lines and hachures. Depths shown by bathymetric isolines and soundings. | \\\\ $a \"Nota, le de\u0301tail de la ville, emprunte\u0301 au plan local espangnol, a e\u0301te\u0301 rectifie\u0301 par la triangulation et le nivellement effectue\u0301s par la",
"location": " ",
"bathLines": " ",
"bathInterv": " ",
"instCallNo": " ",
"setTitle": "French Charts",
"sheetId": 21511,
"digita": "agsmap026454",
"titleAlt": "Tangier, port, 1908",
"Shape_Length": 21584.807399988174,
"Shape_Area": 28676605.202176783
},
"geometry": {
"rings": [
[
[
-648590.64440000057,
4269019.7031000033
],
[
-648590.64440000057,
4275081.0283999965
],
[
-643859.56599999964,
4275081.0283999965
],
[
-643859.56599999964,
4269019.7031000033
],
[
-648590.64440000057,
4269019.7031000033
]
]
]
}
}
]
}
js
function exportJSONToCSV(objArray) {
var arr = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
var str =
`${Object.keys(arr[0])
.map((value) => `"${value}"`)
.join(',')}` + '\r\n';
var csvContent = arr.reduce((st, next) => {
console.log(next);
st +=
`${Object.values(next)
.map((value) => `"${value}"`)
.join(',')}` + '\r\n';
return st;
}, str);
var element = document.createElement('a');
element.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
element.target = '_blank';
element.download = 'export.csv';
element.click();
}
What about:
var json = ... // YOUR JSON
var features = json.features;
var isFirstIterationCompleted = false;
var csv = '';
features.forEach(e => {
var attributesKeys = Object.keys(e.attributes);
if (!isFirstIterationCompleted) {
csv += attributesKeys.join(';') + '\n'; // separated by semicolon
isFirstIterationCompleted = true;
}
attributesKeys.forEach(a => {
csv += e.attributes[a] + ';';
});
csv += '\n';
})
console.log(csv);
Related
I have this JSON string:
var json = {
"cdl": {
"06A78000000YNR7EAO": {
"attributes": {
"type": "CDL",
"url": "/services/data"
},
"CDI": "06978000000GIjCAAW",
"LEI": "a1U78000000SUtTEAW",
"Id": "06A78000000YNR7EAO",
"CD": {
"attributes": {
"type": "CD",
"url": "/services/data"
},
"Title": "photo-1517849845537-4d257902454a",
"Id": "06978000000GIjCAAW"
}
},
"06A78000000YNPGEA4": {
"attributes": {
"type": "CDL",
"url": "/services/data"
},
"CDI": "06978000000GIhuAAG",
"LEI": "a1U78000000SUtOEAW",
"Id": "06A78000000YNPGEA4",
"CD": {
"attributes": {
"type": "CD",
"url": "/services/data"
},
"Title": "photo-1517519014922-8fc06b814a0e",
"Id": "06978000000GIhuAAG"
}
}
},
"documents": {
"a1U78000000SUtTEAW": {
"attributes": {
"type": "DR",
"url": "/services/data"
},
"Id": "a1U78000000SUtTEAW",
"Name": "test2"
},
"a1U78000000SUtOEAW": {
"attributes": {
"type": "DR",
"url": "/services/data"
},
"Id": "a1U78000000SUtOEAW",
"Name": "test"
}
}
}
I can access to the document name like this:
console.log(Object.values(json)[1]["a1U78000000SUtTEAW"]["Name"]);
how can i know how much documents are and how can i get the name without using "a1U78000000SUtTEAW"?
try this
Object.keys(json.documents).forEach(key => {
console.log("\n" + key + ": " + json.documents[key].Name);
});
or this
var documents= Object.values(json.documents);
console.log(documents.length); //2
console.log(documents[0].Id); // a1U78000000SUtTEAW
console.log(documents[0].Name); // test2
I'm trying to add the collection field (name and family) to my metadata using VSC. Not sure where to begin or how to do it. Any help appreciated. Thanks!
{
"name": "Solflare X NFT",
"symbol": "",
"description": "Celebratory Solflare NFT for the Solflare X launch",
"seller_fee_basis_points": 0,
"image": "https://www.arweave.net/abcd5678?ext=png",
"animation_url": "https://www.arweave.net/efgh1234?ext=mp4",
"external_url": "https://solflare.com",
"attributes": [
{ "trait_type": "web", "value": "yes" },
{ "trait_type": "mobile", "value": "yes" },
{ "trait_type": "extension", "value": "yes" }
],
"collection": { "name": "Solflare X NFT", "family": "Solflare" },
"properties": {
"files": [
{
"uri": "https://www.arweave.net/abcd5678?ext=png",
"type": "image/png"
},
{
"uri": "https://watch.videodelivery.net/9876jkl",
"type": "unknown",
"cdn": true
},
{ "uri": "https://www.arweave.net/efgh1234?ext=mp4", "type": "video/mp4" }
],
"category": "video",
"creators": [
{ "address": "SOLFLR15asd9d21325bsadythp547912501b", "share": 100 }
]
}
}
Hi Here i am having a object that is returned from api.
let ApiData1 = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 10,
"stateId": 10,
"name": "Tamil Nadu",
"code": "TN"
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 11,
"stateId": 11,
"name": "Karnataka",
"code": "KA"
}
},
null,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 12,
"stateId": 12,
"name": "Pondicherry",
"code": "PY"
}
},
null,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 1,
"stateId": 1,
"name": "Delhi",
"code": "DL"
}
}
]
}
In this data , in ApiData1.features . there are some null values retuned . I need to remove this null values and has to return like this.
OutPut
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 10,
"stateId": 10,
"name": "Tamil Nadu",
"code": "TN"
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 11,
"stateId": 11,
"name": "Karnataka",
"code": "KA"
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 12,
"stateId": 12,
"name": "Pondicherry",
"code": "PY"
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 1,
"stateId": 1,
"name": "Delhi",
"code": "DL"
}
}
]
}
is anyway to achieve this by passing this ApiData into a function and return like this. Could u please help me with this.
Thanks in advance
Try this , it should help get rid of nulls
ApiData1.features = ApiData1.features.filter(ob => ob !==null)
You can use ES6 spread operator and .filter() to filter the null data, here is a working snippet:
let ApiData1 = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 10,
"stateId": 10,
"name": "Tamil Nadu",
"code": "TN"
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 11,
"stateId": 11,
"name": "Karnataka",
"code": "KA"
}
},
null,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 12,
"stateId": 12,
"name": "Pondicherry",
"code": "PY"
}
},
null,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 1,
"stateId": 1,
"name": "Delhi",
"code": "DL"
}
}
]
}
let newData = {
...ApiData1,
features: ApiData1.features.filter((el) => el)
}
console.log(newData);
Added flavor of Imperative style of coding.
Used forEach loop
In JS object/Arrays are pass by ref.
Updates ApiData1 features data using [...spreadOperator]
var ApiData1 = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 10,
"stateId": 10,
"name": "Tamil Nadu",
"code": "TN"
}
},
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 11,
"stateId": 11,
"name": "Karnataka",
"code": "KA"
}
},
null,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 12,
"stateId": 12,
"name": "Pondicherry",
"code": "PY"
}
},
null,
{
"type": "Feature",
"geometry": {
"type": "MultiPolygon"
},
"properties": {
"color": 1,
"id": 1,
"stateId": 1,
"name": "Delhi",
"code": "DL"
}
}
]
};
var features =[];
ApiData1.features.forEach(feature => feature ? features.push(feature): null);
ApiData1['features'] = [...features];
console.log(ApiData1);
I'm having problems with my code, where I need to pick data with a JSON query from an API.
Here is the JSON body what I receive from the query:
{
"status": "success",
"reservations": [
{
"id": "38199",
"subject": "Koneiden vaihto",
"modifiedDate": "2017-05-16T12:46:17",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "124",
"type": "room",
"code": "FRAMIF407",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F407 (atk 34)"
}
],
"description": ""
},
{
"id": "30505",
"subject": "Alumnitapahtuman etukäteisjärjestelyt",
"modifiedDate": "2017-04-19T09:36:02",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "104",
"type": "room",
"code": "FRAMIF144",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F144 (lasipalatsi 120)"
}
],
"description": ""
},
{
"id": "38864",
"subject": "Koneiden vaihto/säilytystila",
"modifiedDate": "2017-06-21T06:03:07",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "107",
"type": "room",
"code": "FRAMIF211",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F211 (fysioterapia/teoria)"
}
],
"description": ""
},
{
"id": "38335",
"subject": "Koneiden vaihto",
"modifiedDate": "2017-05-16T12:48:32",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "127",
"type": "room",
"code": "FRAMIF410",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F410 (atk 34)"
}
],
"description": ""
},
{
"id": "38426",
"subject": "Koneiden vaihto",
"modifiedDate": "2017-05-16T12:49:25",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "128",
"type": "room",
"code": "FRAMIF411",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F411 (atk 34)"
}
],
"description": ""
},
{
"id": "43898",
"subject": "Varattu plinttien varastointiin",
"modifiedDate": "2017-06-12T08:54:31",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "106",
"type": "room",
"code": "FRAMIF210",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F210 (teoria 36)"
}
],
"description": ""
},
{
"id": "38267",
"subject": "Koneiden vaihto",
"modifiedDate": "2017-06-21T06:03:07",
"startDate": "2017-06-21T08:00:00",
"endDate": "2017-06-21T22:00:00",
"resources": [
{
"id": "126",
"type": "room",
"code": "FRAMIF409",
"parent": {
"id": "4",
"type": "building",
"code": "FramiF",
"name": "Frami F"
},
"name": "Frami F409 (atk 34)"
}
],
"description": ""
}
]
}
I need to pick up the all the names from the body, which are for example :
"Frami F407 (atk 34)", "Frami F144 (lasipalatsi 120)",
"Frami F211 (fysioterapia/teoria)", "Frami F410 (atk 34)
Here's how I process the data in order to get the names;
var jsonQuery = {
"startDate": startDate,
"endDate": endDate,
"building": [building]
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(xhr.responseText);
var rooms = [];
for (var i = 0; i < json.reservations.length; i++) {
if (json.reservations[i].resources != null) {
for (var j = 0; j < json.reservations[i].resources.length; j++) {
var reservation = json.reservations[i];
var resource = json.reservations[i].resources[j];
if (resource.type === "room") {
if (rooms.indexOf("code")) {
rooms.push(resource.name);
}
}
}
}
}
}
};
xhr.open("POST", "URL", true, "API-key", "");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(jsonQuery));
This is how it should work : https://jsfiddle.net/p474djan/3/
But the problem is, when I run it through JSON.parse() and check in the console log, it keeps the first two names ("Frami F407 (atk 34)" and "Frami F144 (lasipalatsi 120)") but removes all the rest of the names. Any idea why this is happening?
I am not able to find any issue on your code but here it is my suggestion you can achieve the same via underscore.js without any looping and so on
https://jsfiddle.net/p474djan/5/
document.getElementById("pageOne").innerHTML = _.pluck(_.flatten(_.pluck(json["reservations"], 'resources')), 'name').join("<br/>")
Please have a look in to this
I have a json file returned on my javascript code. The file looks like this :
{
"data": [
{
"id": "594984240522886",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Ducks",
"description": "ducks",
"link": "http://www.facebook.com/album.php?fbid=594984240522886&id=593959083958735&aid=1073741834",
"cover_photo": "594984260522884",
"count": 4,
"type": "normal",
"created_time": "2013-06-13T15:12:22+0000",
"updated_time": "2013-06-13T15:12:40+0000",
"can_upload": false
},
{
"id": "593963787291598",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Profile Pictures",
"link": "http://www.facebook.com/album.php?fbid=593963787291598&id=593959083958735&aid=1073741832",
"cover_photo": "593963797291597",
"count": 1,
"type": "profile",
"created_time": "2013-06-11T16:52:29+0000",
"updated_time": "2013-06-11T16:52:31+0000",
"can_upload": false
},
{
"id": "593963467291630",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Goats",
"description": "goats",
"link": "http://www.facebook.com/album.php?fbid=593963467291630&id=593959083958735&aid=1073741831",
"cover_photo": "593963477291629",
"count": 7,
"type": "normal",
"created_time": "2013-06-11T16:51:56+0000",
"updated_time": "2013-06-11T16:52:02+0000",
"can_upload": false
},
{
"id": "593962700625040",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Dogs",
"description": "dogs",
"link": "http://www.facebook.com/album.php?fbid=593962700625040&id=593959083958735&aid=1073741830",
"cover_photo": "593962710625039",
"count": 10,
"type": "normal",
"created_time": "2013-06-11T16:50:27+0000",
"updated_time": "2013-06-11T16:50:37+0000",
"can_upload": false
},
{
"id": "593961937291783",
"from": {
"id": "593959083958735",
"category": "Community",
"name": "Decoc"
},
"name": "Cows",
"description": "Cows",
"link": "http://www.facebook.com/album.php?fbid=593961937291783&id=593959083958735&aid=1073741829",
"cover_photo": "593961983958445",
"count": 5,
"type": "normal",
"created_time": "2013-06-11T16:48:26+0000",
"updated_time": "2013-06-11T16:49:32+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NTkzOTYxOTM3MjkxNzgz",
"before": "NTk0OTg0MjQwNTIyODg2"
}
}
}
I would like to loop inside the "data" and see how many different data elements exist(as you see each element has an id , from , name , description..) . How can i do that with javascript?
You can try the following code:
for(i=0;json.data.length;i++){
var element = json.data[i];
}
or also in this other way:
for (i in json.data) {
if (json.data.hasOwnProperty(i)) {
var element = json.data[i];
}
}