Programmatically find the JSONPath of a node which matches a given attribute - javascript

I have a nested JSON object where I am trying to search for an attribute value. If there is a match, I would like to print the entire JSONPath just in the form of XPath.
Below is my JSON:
{
"_declaration": {
"_attributes": {
"version": "1.0",
"encoding": "UTF-8",
"standalone": "yes"
}
},
"hierarchy": {
"_attributes": {
"index": "0",
"class": "hierarchy",
"rotation": "0",
"width": "1440",
"height": "3036"
},
"android.widget.FrameLayout": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.FrameLayout",
"text": "",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[37,1017][1403,2102]",
"displayed": "true"
},
"android.widget.FrameLayout": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.FrameLayout",
"text": "",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[37,1017][1403,2102]",
"displayed": "true"
},
"android.widget.FrameLayout": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.FrameLayout",
"text": "",
"resource-id": "android:id/content",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[37,1017][1403,2102]",
"displayed": "true"
},
"android.widget.ScrollView": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.ScrollView",
"text": "",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "true",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[37,1017][1403,2102]",
"displayed": "true"
},
"android.widget.LinearLayout": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.LinearLayout",
"text": "",
"resource-id": "com.android.permissioncontroller:id/grant_singleton",
"checkable": "false",
"checked": "false",
"clickable": "true",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[37,1017][1403,2102]",
"displayed": "true"
},
"android.widget.LinearLayout": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.LinearLayout",
"text": "",
"resource-id": "com.android.permissioncontroller:id/grant_dialog",
"checkable": "false",
"checked": "false",
"clickable": "true",
"enabled": "true",
"focusable": "true",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[37,1017][1403,2102]",
"displayed": "true"
},
"android.widget.LinearLayout": [
{
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.LinearLayout",
"text": "",
"resource-id": "com.android.permissioncontroller:id/content_container",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[93,1073][1347,1549]",
"displayed": "true"
},
"android.widget.LinearLayout": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.LinearLayout",
"text": "",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[177,1136][1263,1465]",
"displayed": "true"
},
"android.widget.ImageView": {
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.ImageView",
"text": "",
"resource-id": "com.android.permissioncontroller:id/permission_icon",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[664,1136][776,1248]",
"displayed": "true"
}
},
"android.widget.TextView": {
"_attributes": {
"index": "1",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.TextView",
"text": "Allow Oscar to send you notifications?",
"resource-id": "com.android.permissioncontroller:id/permission_message",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[177,1290][1263,1465]",
"displayed": "true"
}
}
}
},
{
"_attributes": {
"index": "1",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.LinearLayout",
"text": "",
"checkable": "false",
"checked": "false",
"clickable": "false",
"enabled": "true",
"focusable": "false",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[93,1549][1347,2046]",
"displayed": "true"
},
"android.widget.Button": [
{
"_attributes": {
"index": "0",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.Button",
"text": "Allow",
"resource-id": "com.android.permissioncontroller:id/permission_allow_button",
"checkable": "false",
"checked": "false",
"clickable": "true",
"enabled": "true",
"focusable": "true",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[177,1556][1263,1752]",
"displayed": "true"
}
},
{
"_attributes": {
"index": "1",
"package": "com.google.android.permissioncontroller",
"class": "android.widget.Button",
"text": "Don’t allow",
"resource-id": "com.android.permissioncontroller:id/permission_deny_button",
"checkable": "false",
"checked": "false",
"clickable": "true",
"enabled": "true",
"focusable": "true",
"focused": "false",
"long-clickable": "false",
"password": "false",
"scrollable": "false",
"selected": "false",
"bounds": "[177,1766][1263,1962]",
"displayed": "true"
}
}
]
}
]
}
}
}
}
}
}
}
}
I would like to find the path to the element, which has property "text: "Don't allow" for its _attributes key.
So, my expected output will be:
/hierarchy/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.ScrollView/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.widget.Button[2]
I am using Javascript.

Related

Cannot get json to loop properly in javascript

I cannot figure out how to loop though this JSON return properly. It seems formatted properly but using JSON.Parse() just isnt working for me. It does work for the first two $POST variables that are returned and I can use them without issue. Im wondering if im having so many issues because I'm getting this JSON return from the echo'd JSON array that im echoing out back to the ajax. Whats strange to me is that ive saved this to a local.json file and I can parse it without issue.
{
"0": {
"Name": "QG",
"Guid": "3e2e4830-7954-4248-b580-03aa04f3add8",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"1": {
"Name": "OR",
"Guid": "51f61b92-2b88-4820-a3a4-042c79844e5d",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"2": {
"Name": "4O",
"Guid": "90ccb0c9-ab7a-4d3e-94d0-09a9983bbce7",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"3": {
"Name": "VV",
"Guid": "16047f72-2ee0-4cc0-acd8-0c19e9a2694c",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"4": {
"Name": "5F",
"Guid": "4e7bcd95-44fd-4d10-a586-14a5e77f6e22",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"5": {
"Name": "FR",
"Guid": "1ca5a5ce-ac5c-4fd7-8f10-14a8585d4de9",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"6": {
"Name": "6B",
"Guid": "f76307dd-4500-4ace-a756-1b4b207801c2",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"7": {
"Name": "AK",
"Guid": "3ffbb7a5-e5a4-458f-a9c7-1f8a29df58dc",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"8": {
"Name": "MK",
"Guid": "e51e3daa-d10f-43ce-b3ce-202bb9e5f227",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"9": {
"Name": "VH",
"Guid": "c332aa7b-0a3a-4b24-920a-20e4273c7902",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
},
"10": {
"Name": "3K",
"Guid": "d33da5b4-29cf-401f-8880-27d773d56d2b",
"TypeName": "PresentationFolder",
"LongTypeName": "Altiris.NS.ItemManagement.PresentationFolder",
"TypeGuid": "f1e8956a-a158-487f-8185-4c3b492734e7",
"ParentFolderName": "HELLO_WORLD",
"ParentFolderGuid": "e3ceea75-510e-4900-bb5f-6b0d47309bd3",
"Attributes": "Normal",
"Enabled": "false",
"IsSchedulableItem": "false",
"ScheduleEnabled": "false",
"SharedScheduleGuid": "00000000-0000-0000-0000-000000000000"
}
UPDATE:
I was finally able to to get better results and get the JSON displaying correctly. By setting my variable to var json = data.body[0]; and outputting like this $('.modal-body').html('<pre>' + JSON.stringify(json, null, 2) + '</pre>');
I just cant figure out this .each() statement now to iterate though all of the objects I only get the last value at the bottom of this JSON.
FINAL CODE IT WORKS :D
if (data.body[0][1] !== undefined) {
var json = data.body[0];
} else {
var json = data.body;
}
const mappedItems = $.map(json, function(item) {
const html = `<div class='table-responsive' style='padding-top:20px;'>
<table class="table color-bordered-table info-bordered-table">
<thead>
<tr style="white-space: nowrap; text-align: center;">
<th>IATA</th>
<th>Guid</th>
<th>Type Name</th>
<th>Long Type Name</th>
<th>Type Guid</th>
<th>Parent Folder Name</th>
<th>Parent Folder Guid</th>
<th>Attributes</th>
<th>Enabled</th>
<th>Is Scheduled Item</th>
<th>Schedule Enabled</th>
<th>Drill Down</th>
</tr>
</thead>
<tbody>
<tr>
<td>${item.Name}</td>
<td>${item.Guid}</td>
<td>${item.TypeName}</td>
<td style="inline-size: 160px;word-break: break-all;">${item.LongTypeName}</td>
<td>${item.TypeGuid}</td>
<td>${item.ParentFolderName}</td>
<td>${item.ParentFolderGuid}</td>
<td>${item.Attributes}</td>
<td>${item.Enabled}</td>
<td>${item.IsSchedulableItem}</td>
<td>${item.ScheduleEnabled}</td>
<td><button type="button" name="'.$value->Name.'" value="'.$value->Guid.'" class="btn btn-primary"
style="width:150px" onclick="modalData(this)">Full screen</button></td>
</tr>
</tbody>
</table>
</div>`;
return `${html}`;
});
$('.modal-body').html(mappedItems);
The issue is that you are setting the inner HTML value for the .modal-body element on each iteration of your $.each loop. This means that, upon completion of the loop, the inner HTML of .modal-body will be the data corresponding to only the last item in your parsed JSON.
The approach I would take to this problem is to use $.map instead of $.each. I would map the first-level properties of the parsed JSON into the values I want to inject into the HTML of .modal-body. I would then join these array elements with a suitable delimiter, which will produce a string I can insert into .modal-body.html().
The result would look something like:
const mappedItems = $.map(json, function(item) {
return `${item.Name}`;
});
$('.modal-body').html(mappedItems.join('<br>'));
Here is a fiddle for reference.

How to solve SyntaxError: Unexpected token ^ in JSON at position error?

I am receiving a dynamic data string from the python kernel, (however, it's an object but the python kernel can only send it as a sting due to the limitation of the python backend that cant be changed due to a third-party package), below is the console.log output.
[{"model_class": "DataToolParameter", "name": "input_file", "argument": null, "type": "data", "label": "VCF/BCF Data", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": null, "extensions": ["vcf", "vcf_bgzip", "bcf"], "edam": {"edam_formats": ["format_3016", "format_3016", "format_3020"], "edam_data": ["data_0006", "data_0006", "data_3498"]}, "multiple": false, "options": {"hda": [], "hdca": []}, "default_value": null, "text_value": "No dataset."}, {"model_class": "Section", "name": "sec_required", "type": "section", "title": "Required References", "help": null, "expanded": true, "inputs": [{"model_class": "Conditional", "name": "reference_source", "type": "conditional", "cases": [{"model_class": "ConditionalWhen", "value": "cached", "inputs": [{"model_class": "SelectToolParameter", "name": "fasta_ref", "argument": null, "type": "select", "label": "Reference genome", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": true, "value": null, "options": [], "display": null, "multiple": false, "textable": false, "default_value": null, "text_value": "None"}]}, {"model_class": "ConditionalWhen", "value": "history", "inputs": [{"model_class": "DataToolParameter", "name": "fasta_ref", "argument": null, "type": "data", "label": "Reference genome", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "extensions": ["fasta"], "edam": {"edam_formats": ["format_1929"], "edam_data": ["data_2044"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as fasta)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta", "tags": [], "src": "hda", "keep": false}, {"id": "47f5e6f7acd01631", "hid": 3, "name": "Extract MAF blocks on data 2 (as fasta)", "tags": [], "src": "hda", "keep": false}, {"id": "695fd3e24b533dbc", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as fasta)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "text_value": "No dataset."}]}], "test_param": {"model_class": "SelectToolParameter", "name": "reference_source_selector", "argument": null, "type": "select", "label": "Choose the source for the reference genome", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": "cached", "options": [["Use a built-in genome", "cached", false], ["Use a genome from the history", "history", false]], "display": null, "multiple": false, "textable": false, "text_value": "Use a built-in genome"}}, {"model_class": "DataToolParameter", "name": "gff_annot", "argument": null, "type": "data", "label": "GFF3 annotation file", "help": "From Ensembl: ftp://ftp.ensembl.org/pub/current_gff3/", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": null, "extensions": ["gff3"], "edam": {"edam_formats": ["format_1975"], "edam_data": ["data_1255"]}, "multiple": false, "options": {"hda": [], "hdca": []}, "default_value": null, "text_value": "No dataset."}]}, {"model_class": "Section", "name": "sec_csq_opts", "type": "section", "title": "CSQ Options", "help": null, "expanded": true, "inputs": [{"model_class": "IntegerToolParameter", "name": "ncsq", "argument": null, "type": "integer", "label": "maximum number of consequences to consider per site", "help": "-ncsq 16", "refresh_on_change": false, "min": 1, "max": 50, "optional": false, "hidden": false, "is_dynamic": false, "value": "16", "area": false, "datalist": [], "default_value": "16", "text_value": "16"}, {"model_class": "BooleanToolParameter", "name": "local_csq", "argument": null, "type": "boolean", "label": "run localized predictions considering only one VCF record at a time", "help": "--local-csq switch off haplotype-aware calling, run localized predictions considering only one VCF record at a time", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "false", "truevalue": "--local-csq", "falsevalue": "", "default_value": "false", "text_value": "false"}, {"model_class": "SelectToolParameter", "name": "phase", "argument": null, "type": "select", "label": "phase", "help": "how to construct haplotypes and how to deal with unphased data", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "options": [["take GTs as is, create haplotypes regardless of phase (0/1 -> 0|1)", "a", false], ["merge *all* GTs into a single haplotype (0/1 -> 1, 1/2 -> 1)", "m", false], ["require phased GTs, throw an error on unphased het GTs", "r", false], ["create non-reference haplotypes if possible (0/1 -> 1|1, 1/2 -> 1|2)", "R", false], ["skip unphased GTs", "s", false]], "display": null, "multiple": false, "textable": false, "default_value": null, "text_value": "Nothing selected."}, {"model_class": "TextToolParameter", "name": "custom_tag", "argument": null, "type": "text", "label": "use this custom tag to store consequences rather than the default BCSQ tag", "help": "", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": [], "default_value": "", "text_value": "Empty."}]}, {"model_class": "Section", "name": "sec_restrict", "type": "section", "title": "Restrict to", "help": null, "expanded": false, "inputs": [{"model_class": "Conditional", "name": "regions", "type": "conditional", "cases": [{"model_class": "ConditionalWhen", "value": "__none__", "inputs": []}, {"model_class": "ConditionalWhen", "value": "regions", "inputs": [{"model_class": "Repeat", "name": "regions", "type": "repeat", "title": "Region Filter", "help": null, "default": 1, "min": 1, "max": "__Infinity__", "inputs": [{"model_class": "TextToolParameter", "name": "chrom", "argument": null, "type": "text", "label": "Region chromosome", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "start", "argument": null, "type": "text", "label": "Region start position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "stop", "argument": null, "type": "text", "label": "Region end position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}], "cache": {}}]}, {"model_class": "ConditionalWhen", "value": "regions_file", "inputs": [{"model_class": "DataToolParameter", "name": "regions_file", "argument": null, "type": "data", "label": "Regions File", "help": "restrict to Regions listed in a file", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "extensions": ["tabular"], "edam": {"edam_formats": ["format_3475"], "edam_data": ["data_0006"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "955b0e088867ea92", "hid": 10, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta (as tabular)", "tags": [], "src": "hda", "keep": false}, {"id": "3ba2ccc043967969", "hid": 3, "name": "Extract MAF blocks on data 2 (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "57c61e66a8a42935", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "1d6404f66ed3d72e", "hid": 1, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "text_value": "No dataset."}]}], "test_param": {"model_class": "SelectToolParameter", "name": "regions_src", "argument": null, "type": "select", "label": "Regions", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": "__none__", "options": [["Do not restrict to Regions", "__none__", false], ["Specify one or more Region(s) directly", "regions", false], ["Operate on Regions specified in a history dataset", "regions_file", false]], "display": null, "multiple": false, "textable": false, "text_value": "Do not restrict to Regions"}}, {"model_class": "Conditional", "name": "targets", "type": "conditional", "cases": [{"model_class": "ConditionalWhen", "value": "__none__", "inputs": []}, {"model_class": "ConditionalWhen", "value": "targets", "inputs": [{"model_class": "Repeat", "name": "targets", "type": "repeat", "title": "Target Filter", "help": null, "default": 1, "min": 1, "max": "__Infinity__", "inputs": [{"model_class": "TextToolParameter", "name": "chrom", "argument": null, "type": "text", "label": "Target chromosome", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "start", "argument": null, "type": "text", "label": "Target start position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}, {"model_class": "TextToolParameter", "name": "stop", "argument": null, "type": "text", "label": "Target end position", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": []}], "cache": {}}]}, {"model_class": "ConditionalWhen", "value": "targets_file", "inputs": [{"model_class": "DataToolParameter", "name": "targets_file", "argument": null, "type": "data", "label": "Targets File", "help": "restrict to Targets listed in a file", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "extensions": ["tabular"], "edam": {"edam_formats": ["format_3475"], "edam_data": ["data_0006"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "955b0e088867ea92", "hid": 10, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta (as tabular)", "tags": [], "src": "hda", "keep": false}, {"id": "3ba2ccc043967969", "hid": 3, "name": "Extract MAF blocks on data 2 (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "57c61e66a8a42935", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "1d6404f66ed3d72e", "hid": 1, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": {"values": [{"id": "0b378429c2c91c4f", "src": "hda"}]}, "text_value": "No dataset."}]}], "test_param": {"model_class": "SelectToolParameter", "name": "targets_src", "argument": null, "type": "select", "label": "Targets", "help": "", "refresh_on_change": true, "optional": false, "hidden": false, "is_dynamic": false, "value": "__none__", "options": [["Do not restrict to Targets", "__none__", false], ["Specify one or more Target(s) directly", "targets", false], ["Operate on Targets specified in a history dataset", "targets_file", false]], "display": null, "multiple": false, "textable": false, "text_value": "Do not restrict to Targets"}}, {"model_class": "TextToolParameter", "name": "include", "argument": "--include", "type": "text", "label": "Include", "help": "Select sites for which the expression is true", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "area": false, "datalist": [], "default_value": null, "text_value": "Not available."}, {"model_class": "TextToolParameter", "name": "exclude", "argument": "--exclude", "type": "text", "label": "Exclude", "help": "Exclude sites for which the expression is true", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "area": false, "datalist": [], "default_value": null, "text_value": "Not available."}]}, {"model_class": "Section", "name": "sec_subset", "type": "section", "title": "Subset Options", "help": null, "expanded": false, "inputs": [{"model_class": "TextToolParameter", "name": "samples", "argument": "--samples", "type": "text", "label": "Samples", "help": "Comma separated list of samples to annotate (or exclude)", "refresh_on_change": false, "optional": true, "hidden": false, "is_dynamic": false, "value": "", "area": false, "datalist": [], "default_value": "", "text_value": "Empty."}, {"model_class": "BooleanToolParameter", "name": "invert_samples", "argument": null, "type": "boolean", "label": "Invert Samples", "help": "Inverts the query/filtering applied by Samples (adds \\"^\\" prefix to exclude)", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "false", "truevalue": "^", "falsevalue": "", "default_value": "false", "text_value": "false"}, {"model_class": "DataToolParameter", "name": "samples_file", "argument": "--samples_file", "type": "data", "label": "Samples file", "help": "File of samples to include", "refresh_on_change": true, "optional": true, "hidden": false, "is_dynamic": false, "value": null, "extensions": ["tabular"], "edam": {"edam_formats": ["format_3475"], "edam_data": ["data_0006"]}, "multiple": false, "options": {"hda": [{"id": "0b378429c2c91c4f", "hid": 11, "name": "UCSC Main on Human: multiz100way (chrX:15,578,261-15,621,068) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "955b0e088867ea92", "hid": 10, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}, {"id": "33d7a2c94fd36485", "hid": 9, "name": "non_ACPs.fasta (as tabular)", "tags": [], "src": "hda", "keep": false}, {"id": "3ba2ccc043967969", "hid": 3, "name": "Extract MAF blocks on data 2 (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "57c61e66a8a42935", "hid": 2, "name": "UCSC Main on Human: multiz100way (chrX:15,560,138-15,602,945) (as interval)", "tags": [], "src": "hda", "keep": false}, {"id": "1d6404f66ed3d72e", "hid": 1, "name": "UCSC Main on Human: knownGene (genome)", "tags": [], "src": "hda", "keep": false}], "hdca": []}, "default_value": null, "text_value": "No dataset."}, {"model_class": "BooleanToolParameter", "name": "invert_samples_file", "argument": null, "type": "boolean", "label": "Invert Samples file", "help": "inverts the query/filtering applied by Samples file", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "false", "truevalue": "^", "falsevalue": "", "default_value": "false", "text_value": "false"}]}, {"model_class": "SelectToolParameter", "name": "output_type", "argument": null, "type": "select", "label": "", "help": "", "refresh_on_change": false, "optional": false, "hidden": false, "is_dynamic": false, "value": "b", "options": [["compressed BCF", "b", false], ["uncompressed VCF", "v", false]], "display": null, "multiple": false, "textable": false, "default_value": "b", "text_value": "compressed BCF"}]
I am trying to convert this dynamic string to an object using
JSON.parse(Kernel_inputs_as_string)
It works perfectly for all the cases except a few in which string contains "^" char. It throws an error.
SyntaxError: Unexpected token ^ in JSON at position 13477 error
On the other hand, when I copy and save the console.log string as input and trying JSON.parse() it work perfectly as described below.
const json = '[{"model_class": "DataToolParameter", "name": "input_file".....}]'
const obj = JSON.parse(json);
console.log(obj[0]);
I'm not able to understand why this error is coming and how to solve it for similar cases where the string has "^" char.
Please help me to solve this error.
Thank you

How to filter parent json from child's Id in javascript/vuejs

So I have this json.
{
"account_owner": "",
"account_type": "",
"nest_uid": "17_15_1536914882_yhHDzQsDSI",
"business_name": "",
"sync_block": false,
"validation": {
"isError": false,
"inputList": [],
"message": ""
},
"is_selected": true,
"contacts": [{
"con_title": "",
"con_fName": "",
"con_lName": "",
"con_job_title": "",
"is_selected": true,
"emails": [{
"email": "",
"type": "",
"primary": false,
"is_selected": true,
"nest_uid": "17_15_1536914882_yhHDzQsDSK",
"validation": {
"isError": false,
"inputList": [],
"message": "",
"is_selected": true
},
"checked": false
}],
"phones": [{
"phone": "",
"type": "",
"primary": false,
"is_selected": true,
"nest_uid": "17_15_1536914882_uHN38SxJ3s",
"validation": {
"isError": false,
"inputList": [],
"is_selected": true,
"message": ""
},
"checked": false
}],
"nest_uid": "17_15_1536914882_hwzB7dIn9v",
"checked": false
},
{
"con_title": "",
"con_fName": "",
"con_lName": "",
"con_job_title": "",
"is_selected": true,
"emails": [{
"email": "",
"type": "",
"primary": false,
"is_selected": true,
"nest_uid": "17_15_1536914882_yhHDzQsDSx",
"validation": {
"isError": false,
"is_selected": true,
"inputList": [],
"message": ""
},
"checked": false
}],
"phones": [{
"phone": "",
"type": "",
"primary": false,
"is_selected": true,
"nest_uid": "17_15_1536914882_uHN38SxJ3Y",
"validation": {
"isError": false,
"is_selected": true,
"inputList": [],
"message": ""
},
"checked": false
}],
"nest_uid": "17_15_1536914882_hwzB7dIn9x",
"checked": false
}
]
}
you can see that there are two property on every level
nest_uid
is_selected
Now I am getting the child element's nest_uid , So I need to mark all the is_selected as false except the one selected and its parent.
For example
if nest_id = '17_15_1536914882_yhHDzQsDSK'
Output
{
"account_owner": "",
"account_type": "",
"nest_uid": "17_15_1536914882_yhHDzQsDSI",
"business_name": "",
"sync_block": false,
"validation": {
"isError": false,
"inputList": [],
"message": ""
},
"is_selected": true,//here
"contacts": [{
"con_title": "",
"con_fName": "",
"con_lName": "",
"con_job_title": "",
"is_selected": true, //here
"emails": [{
"email": "",
"type": "",
"primary": false,
"is_selected": true,
"nest_uid": "17_15_1536914882_yhHDzQsDSK", //here
"validation": {
"isError": false,
"inputList": [],
"message": "",
"is_selected": true
},
"checked": false
}],
"phones": [{
"phone": "",
"type": "",
"primary": false,
"is_selected": false,
"nest_uid": "17_15_1536914882_uHN38SxJ3s",
"validation": {
"isError": false,
"inputList": [],
"is_selected": true,
"message": ""
},
"checked": false
}],
"nest_uid": "17_15_1536914882_hwzB7dIn9v",
"checked": false
},
{
"con_title": "",
"con_fName": "",
"con_lName": "",
"con_job_title": "",
"is_selected": false,
"emails": [{
"email": "",
"type": "",
"primary": false,
"is_selected": false,
"nest_uid": "17_15_1536914882_yhHDzQsDSx",
"validation": {
"isError": false,
"is_selected": false,
"inputList": [],
"message": ""
},
"checked": false
}],
"phones": [{
"phone": "",
"type": "",
"primary": false,
"is_selected": false,
"nest_uid": "17_15_1536914882_uHN38SxJ3Y",
"validation": {
"isError": false,
"is_selected": false,
"inputList": [],
"message": ""
},
"checked": false
}],
"nest_uid": "17_15_1536914882_hwzB7dIn9x",
"checked": false
}
]
}
Recursion is indeed the answer here. Something like this should work, even if it's not the prettiest:
function selectInJSON(uid, current) {
current.is_selected = current.nest_uid === uid
Object.values(current).forEach((child) => {
if (Array.isArray(child)) {
child.forEach((item) => {
selectInJSON(uid, item)
if (item.is_selected) current.is_selected = true
})
}
else if (Object(child) === child) {
selectInJSON(uid, child)
if (child.is_selected) current.is_selected = true
}
})
}

Return list of properties using ng-repeat (AngularJS)

I am trying to convert a working JavaScript/Jquery feature to AngularJS (1.0) so I can add it to a fairly large AngularJS application. I am having some issues getting data to the view using ng-repeat and not sure where my issue is. I was reading through $index documentation and not sure if this is the source of my issue or what I need to do. Also not getting anything in the console for the response.data.deviceList object.
Possible I have a few issues going on here.
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Building Layout - Drag and Drop</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="interact.js"></script>
<script src="angular.min.js"></script>
<script src="mainScripts.js"></script>
</head>
<body>
<div ng-app="mainApp">
<div class="tile draggable" ng-controller="mainScripts" ng-repeat="stuff in titles">
<ul>
<li>{{stuff.location}}</li>
<li>{{stuff.description}}</li>
</ul>
</div>
</div>
</body>
</html>
JavaScript
var mainApp = angular.module('mainApp',[]);
mainApp.controller('mainScripts', function($scope, $http) {
$http.get('devices.json').then(function successCallback(response){
console.log("API call works!");
console.dir(response.data.deviceList);
var titles = response.data.deviceList;
});
}, function errorCallback(response) {
console.log("API call doesn't work");
});
JSON
{
"deviceTypes": [{
"description": "Air Handler",
"typeName": "AirSource"
}, {
"description": "VAV Terminal",
"typeName": "AirTerminal"
}, {
"description": "Fan Coil",
"typeName": "ChilledWaterTerminal"
}, {
"description": "Chiller",
"typeName": "ChilledWaterSource"
}, {
"description": "Generic Unit",
"typeName": "NoResources"
}, {
"description": "Other Source",
"typeName": "OtherSource"
}, {
"description": "Other Terminal",
"typeName": "OtherTerminal"
}, {
"description": "Water Manager",
"typeName": "WaterSource"
}, {
"description": "WSHP Terminal",
"typeName": "WaterTerminal"
}],
"deviceList": [{
"href": "../MISRest/devices/3101117",
"location": "Loc Desk 3 VAV",
"description": "VAV 117",
"objectName": "VAV 117",
"instance": "3101117",
"occupancy": "Occupied",
"schedule": "Standard Schedule",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "None",
"macaddress": "117",
"directSchedule": "True",
"rogueZone": "False",
"parentID": {
"air": "0"
},
"deviceType": ["AirTerminal"]
}, {
"href": "../MISRest/devices/3101121",
"location": "Loc Desk 4 with temp VAV",
"description": "VAV 121",
"objectName": "VAV Actuator Series 2 Bacnet ASC Controller",
"instance": "3101121",
"occupancy": "Error",
"schedule": "Standard Schedule",
"ignore": "False",
"commStatus": "Fault",
"alarmStatus": "Active",
"macaddress": "121",
"directSchedule": "True",
"rogueZone": "False",
"parentID": {
"air": "0"
},
"deviceType": ["AirTerminal"]
}, {
"href": "../MISRest/devices/3101004",
"location": "New Paris",
"description": "KMC Device",
"objectName": "BAC-8205_001635",
"instance": "3101004",
"occupancy": "Error",
"schedule": "Standard Schedule",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "None",
"macaddress": "4",
"directSchedule": "True",
"rogueZone": "False",
"deviceType": ["NoResources"]
}, {
"href": "../MISRest/devices/3101013",
"location": "Default Location",
"description": "VAV-013",
"objectName": "DEFAULT",
"instance": "3101013",
"occupancy": "Occupied",
"schedule": "None",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "None",
"macaddress": "13",
"directSchedule": "True",
"rogueZone": "False",
"parentID": {
"air": "0"
},
"deviceType": ["AirTerminal"]
}, {
"href": "../MISRest/devices/3101066",
"location": "Loc Desk AHU (1st)",
"description": "Desk AHU 066 (2nd)",
"objectName": "POL904_015413",
"instance": "3101066",
"occupancy": "Occupied",
"schedule": "None",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "Active",
"macaddress": "66",
"directSchedule": "False",
"rogueZone": "False",
"deviceType": ["AirSource"]
}]
}
You are declaring the controller inside the ng-repeat (which is incorrect, you need only one controller instance for handling the entire collection, and not one (controller) instance for every element in the collection), so change
this <div ng-app="mainApp">
to <div ng-app="mainApp" ng-controller="mainScripts">
and this <div class="tile draggable" ng-controller="mainScripts" ng-repeat="stuff in titles">
to this <div class="tile draggable" ng-repeat="stuff in titles">
Also, you misplaced the error callback...see below working sample (mocked data)
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainScripts', function($scope, $http) {
var data = {
"deviceTypes": [{
"description": "Air Handler",
"typeName": "AirSource"
}, {
"description": "VAV Terminal",
"typeName": "AirTerminal"
}, {
"description": "Fan Coil",
"typeName": "ChilledWaterTerminal"
}, {
"description": "Chiller",
"typeName": "ChilledWaterSource"
}, {
"description": "Generic Unit",
"typeName": "NoResources"
}, {
"description": "Other Source",
"typeName": "OtherSource"
}, {
"description": "Other Terminal",
"typeName": "OtherTerminal"
}, {
"description": "Water Manager",
"typeName": "WaterSource"
}, {
"description": "WSHP Terminal",
"typeName": "WaterTerminal"
}],
"deviceList": [{
"href": "../MISRest/devices/3101117",
"location": "Loc Desk 3 VAV",
"description": "VAV 117",
"objectName": "VAV 117",
"instance": "3101117",
"occupancy": "Occupied",
"schedule": "Standard Schedule",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "None",
"macaddress": "117",
"directSchedule": "True",
"rogueZone": "False",
"parentID": {
"air": "0"
},
"deviceType": ["AirTerminal"]
}, {
"href": "../MISRest/devices/3101121",
"location": "Loc Desk 4 with temp VAV",
"description": "VAV 121",
"objectName": "VAV Actuator Series 2 Bacnet ASC Controller",
"instance": "3101121",
"occupancy": "Error",
"schedule": "Standard Schedule",
"ignore": "False",
"commStatus": "Fault",
"alarmStatus": "Active",
"macaddress": "121",
"directSchedule": "True",
"rogueZone": "False",
"parentID": {
"air": "0"
},
"deviceType": ["AirTerminal"]
}, {
"href": "../MISRest/devices/3101004",
"location": "New Paris",
"description": "KMC Device",
"objectName": "BAC-8205_001635",
"instance": "3101004",
"occupancy": "Error",
"schedule": "Standard Schedule",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "None",
"macaddress": "4",
"directSchedule": "True",
"rogueZone": "False",
"deviceType": ["NoResources"]
}, {
"href": "../MISRest/devices/3101013",
"location": "Default Location",
"description": "VAV-013",
"objectName": "DEFAULT",
"instance": "3101013",
"occupancy": "Occupied",
"schedule": "None",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "None",
"macaddress": "13",
"directSchedule": "True",
"rogueZone": "False",
"parentID": {
"air": "0"
},
"deviceType": ["AirTerminal"]
}, {
"href": "../MISRest/devices/3101066",
"location": "Loc Desk AHU (1st)",
"description": "Desk AHU 066 (2nd)",
"objectName": "POL904_015413",
"instance": "3101066",
"occupancy": "Occupied",
"schedule": "None",
"ignore": "False",
"commStatus": "None",
"alarmStatus": "Active",
"macaddress": "66",
"directSchedule": "False",
"rogueZone": "False",
"deviceType": ["AirSource"]
}]
};
$scope.titles = data.deviceList; // mocked, replace with real $http.get
/*
// this is the correct way
$http.get('devices.json').then(function successCallback(response) {
console.log("API call works!");
console.dir(response.data.deviceList);
$scope.titles = response.data.deviceList;
}, function errorCallback(response) { // error callback goes here
console.log("API call doesn't work");
});
*/
}); // <-- removed error call back from here
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainScripts"> <!-- moved controller here! -->
<div class="tile draggable" ng-repeat="stuff in titles"> <!-- removed controller from here -->
<ul>
<li>{{stuff.location}}</li>
<li>{{stuff.description}}</li>
</ul>
</div>
</div>

Converting an array of object - JSON

I have an array on objects like this,
[
{
"link": "link1",
"model": "model1",
"role": "role1",
"access": "true"
},
{
"link": "link1",
"model": "model1",
"role": "role2",
"access": "true"
},
{
"link": "link1",
"model": "model1",
"role": "role3",
"access": "true"
},
{
"link": "link1",
"model": "model1",
"role": "role4",
"access": "true"
},
{
"link": "link1",
"model": "model2",
"role": "role1",
"access": "false"
},
{
"link": "link1",
"model": "model2",
"role": "role2",
"access": "false"
},
{
"link": "link1",
"model": "model2",
"role": "role3",
"access": "false"
},
{
"link": "link1",
"model": "model2",
"role": "role4",
"access": "false"
},
{
"link": "link2",
"model": "model1",
"role": "role1",
"access": "false"
},
{
"link": "link2",
"model": "model1",
"role": "role2",
"access": "true"
},
{
"link": "link2",
"model": "model1",
"role": "role3",
"access": "false"
},
{
"link": "link2",
"model": "model1",
"role": "role4",
"access": "true"
},
{
"link": "link2",
"model": "model2",
"role": "role1",
"access": "false"
},
{
"link": "link2",
"model": "model2",
"role": "role2",
"access": "true"
},
{
"link": "link2",
"model": "model2",
"role": "role3",
"access": "false"
},
{
"link": "link2",
"model": "model2",
"role": "role4",
"access": "true"
}
]
With respect to this question, the input was a CSV sample with very less number of rows. In real I have a large CSV file and I found a way to import it and convert to JSON using d3.js, but the problem is I'm unable to convert it to the desired format. I tried using the data.forEach and the output was really weird and I couldn't understand why I get model2 alone in both the links.
Code:
d3.csv('data.csv', function(data) {
var newData = {};
data.forEach(function(e, i) {
newData[e.link] = {};
newData[e.link][e.model] = {};
})
d3.select('main').append('pre')
.text(JSON.stringify(newData, null, ' '));
});
Output:
{
"link1": {
"model2": {}
},
"link2": {
"model2": {}
}
}
Desired Output:
"link1": {
"model1": {
"role1": true,
"role2": true,
"role3": true,
"role4": true,
},
"model2": {
"role1": false,
"role2": false,
"role3": false,
"role4": false,
}
},
"link2": {
"model1": {
"role1": false,
"role2": true,
"role3": false,
"role4": true,
},
"model2": {
"role1": false,
"role2": true,
"role3": false,
"role4": true,
}
}
Any help will be much appreciated. Thanks in advance.
In your forEach, you're not assigning the role and access pair on each iteration, and you're always emptying each section.
Change your forEach with this...
data.forEach(function(e, i) {
// Check if this "link" already exists exists, if not, create it.
if (!newData[e.link])
newData[e.link] = {};
// Check if this "model" already exists inside of this "link", if not, create it.
if (!newData[e.link][e.model])
newData[e.link][e.model] = {};
newData[e.link][e.model][e.role] = e.access;
});
I hope it helps

Categories

Resources