converting format of JSON - javascript

I am using an AJAX query to Fuseki, that I want to visualize in a D3.js collapsable tree. However Fuseki returns the JSON in a format that the D3.js code does not recognise. like this:
{
"head": {
"vars": [ "s" ]
} ,
"results": {
"bindings": [
{
"s": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#FourCheesesTopping"
},
"p": {
"type": "uri",
"value": "http://www.w3.org/2000/01/rdf-schema#subClassOf"
},
"o": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#CheeseTopping"
}
]
}
}
I need to convert this JSON into this format:
{
"name": "Pizza",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaBase",
"children": [
]
},
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#MeatTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#HotSpicedBeefTopping"
}
]
}
]
}
]
}
I have tried taking the JSON and putting it into a new object with the correct format, but it is not working. Here is my code:
var parent = new Object();
var childArray=[];
var child = [];
function createChildObj(_children, children, depth, id, childName, parent, x, x0, y, y0){
var childObj = new Object();
childObj._children = _children;
childObj.children = children;
childObj.depth = depth;
childObj.id =id;
childObj.name = childName;
childObj.parent= parent;
childObj.x = x;
childObj.x0 = x0;
childObj.y = y;
childObj.y0 = y0;
return childObj;
};
console.log(root.length)
for (var i=0; i<root.length; i++){
var childName = root[i]["s"]["value"];
var childObj = createChildObj("children",null, 1, 2, childName, parent, 190, 190, 180, 180);
child.push(childObj);
}
parent.name = "Pizza";
parent.depth = 0;
parent.id = 3;
parent.children= child;
parent.x0 = root.x0;
parent.x = parent.x0;
parent.y0 = root.y0;
parent.y = parent.y0;
So I am aiming to have parent as the JSON object with the data in the correct format to parse to the d3. sorry its a mess, been fiddling for ages trying to learn D3, and the learning curve is steeper than I had anticipated. Any help would be great! cheers.

Related

Ngx charts bubble chart advice

I am trying to get a bubble chart to populate using ngx-charts. The problem is the swimlane documentation on it is almost non-existent and I haven't been able to find any good examples.
I have read the open source code that swimlane provides and have created what I believe are the appropriate variables in Typescript and have constructed my data points using an example line graph I found using the same tools. However the chart still appears empty on the page.
HTML:
<ngx-charts-bubble-chart
[view]="view"
[results]="bubbleDemoTempData"
[showGridLines]="showGridLines"
[legend]="showLegend"
[legendTitle]="legendTitle"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
[autoScale]="autoScale"
[scheme]="colorScheme"
[minRadius]="minRadius"
[maxRadius]="maxRadius"
(select)="onSelectBubbleInteractivePoint($event)"
*ngIf="dataTypeDisplay == 'GraphForm'"
[#fade]>
</ngx-charts-bubble-chart>
TypeScript:
view: any[] = [700, 400];
// options
showXAxis = true;
showXAxisLabel = true;
showYAxisLabel = true;
showYAxis = true;
gradient = false;
showLegend = true;
legendTitle = "Hi";
xAxisLabel = 'Number';
yAxisLabel = 'Color Value';
showGridLines = true;
autoScale=true;
minRadius = 1;
maxRadius = 1;
colorScheme = {
domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
};
Data Points:
public multi = [
{
"name": "Germany",
"series": [
{
"name": "2010",
"value": 7300000
},
{
"name": "2011",
"value": 8940000
}
]
},
{
"name": "USA",
"series": [
{
"name": "2010",
"value": 7870000
},
{
"name": "2011",
"value": 8270000
}
]
},
{
"name": "France",
"series": [
{
"name": "2010",
"value": 5000002
},
{
"name": "2011",
"value": 5800000
}
]
}
];
I would appreciate if someone could give me some advice on correctly populating the chart.
I was eventually able to get it worked out. I will post the same 3 code snippets from above here in their updated forms.
HTML:
<ngx-charts-bubble-chart
[results]="bubbleDemoTempData"
[view]="view"
[showGridLines]="showGridLines"
[legend]="legend"
[legendTitle]="legendTitle"
[legendPosition]="legendPOsition"
[xAxis]="XAxis"
[yAxis]="YAxis"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
[trimXAxisTicks]="trimXAxisTicks"
[trimYAxisTicks]="trimYAxisTicks"
[maxXAxisTickLength]="maxXAxisTickLength"
[maxYAxisTickLength]="maxYAxisTickLength"
[roundDomains]="roundDomains"
[minRadius]="minRadius"
[maxRadius]="maxRadius"
[autoScale]="autoScale"
[schemeType]="schemeType"
(select)="onSelectBubbleInteractivePoint($event)"
*ngIf="dataTypeDisplay == 'GraphForm'"
[#fade]>
</ngx-charts-bubble-chart>
TypeScript:
view: any[] = [700, 400];
// options
showGridLines = true;
legend = true;
legendTitle = "Dots Mf'er";
legendPosition = "right";
xAxis = true;
yAxis = true;
showXAxisLabel = true;
showYAxisLabel = true;
xAxisLabel = "LR";
yAxisLabel = "Jobs";
trimXAxisTicks = true;
trimYAxisTicks = true;
rotateXAxisTicks = true;
maxXAxisTickLength = 16;
maxYAxisTickLength = 16;
// xAxisTicks;
// yAxisTicks;
roundDomains = false;
maxRadius = 5;
minRadius = 5;
autoScale = true;
schemeType = "ordinal";
tooltipDisabled = false;
Data Points:
public bubbleDemoTempData = [
{
"name": "Example1",
"series": [
{
"name": "a",
"x": 0,
"y": 0,
"r": 1
},
{
"name": "b",
"x":10,
"y":3,
"r":10
}
]
},
{
"name":"Example2",
"series": [
{
"name":"1",
"x":20,
"y":1,
"r":30
},
{
"name":"2",
"x":3,
"y":3,
"r":500
}
]
}
];
This works and definitely answers my question from above. That being said the grid lines are still not appearing but that's an entirely different issue that I may have to post a new ticket for.

Postman JSON parse response body arrays inside arrays

I have this JSON Response from API call
[
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
I am using this code to get the id of the service "Deliver"
var data = JSON.parse(responseBody);
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
}
}
The questions are:
How can I get value from array "options", I need to get the "id":
63775 and store as "item_id" and the "name":"Item" as "item_name" postman variables.
Then I need to select the "options" nested in record
"Item" and select the option "name": "Toothbrush" and store in postman
variable "svc_optn_optn_name" and it's "id" stored in
"svc_optn_optn_id"
Here I am giving my own suggestion for your problem with few lines of code. I am not sure, how are you going to use these values. I also don't know if the outer options array will always have 1 item or more. I have just tried to satisfy your questions.
Please ask/comment, if you have more doubts or I am wrong.
I have created a function getAllPostmanDataFrom(obj) which takes object as parameter which is the value of data[count], gathers necessary info in other object postmanObj and returns it to the caller.
function getAllPostmanDataFrom(obj) {
const item_id = obj.options[0].id;
const item_name = obj.options[0].name;
const svc_optn_optn_name = obj.options[0].options[1].name;
const svc_optn_optn_id = obj.options[0].options[1].id;
const postmanObj = {item_id, item_name, svc_optn_optn_id, svc_optn_optn_name}; // Return object
return postmanObj;
}
var data = [
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
var count = 0;
var obj = data[count];
var postmanObj = getAllPostmanDataFrom(obj);
//var {item_id, item_name, svc_optn_optn_id} = postmanObj;
console. log(postmanObj)
/*
console.log(item_id);
console.log(item_name);
console.log(svc_optn_optn_id);
console.log(svc_optn_optn_name);
*/
Finally, you can use values contained in postmanObj as follows:.
postman.setEnvironmentVariable("item_id", postmanObj.item_id);
postman.setEnvironmentVariable("item_name", postmanObj.item_name);
And so on.
This is the solution
var data = JSON.parse(responseBody);
variable named as data
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
var job1_name = data[count].options[0].name;
postman.setEnvironmentVariable("item_name", job1_name);
var job2_id = data[count].options[0].id;
postman.setEnvironmentVariable("item_id", job2_id);
var job3_id = data[count].options[0].options[1].id;
postman.setEnvironmentVariable("svc_optn_optn_id", job3_id);
var job4_name = data[count].options[0].options[1].name;
postman.setEnvironmentVariable("svc_optn_optn_name", job4_name);
}
const data = JSON.parse(responseBody);
data.forEach(item => {
console.log(item.id); // deliver object id.
item.options.forEach(option => {
console.log(`Option Id ${option.id}`); // option id
postman.setEnvironmentVariable("service_id", option.id);
option.options(optionItem => {
if(optionItem.name == 'Toothbrush'){
postman.setEnvironmentVariable("svc_optn_optn_name", optionItem.name);
postman.setEnvironmentVariable("svc_optn_optn_id", optionItem.id);
}
});
});
});

Dimple.js doesn't like my Array

I have data.json in this format:
{
"Users": [
{
"userName": "Herbie",
"weigh-in data": [
{ "date": "2016.01.04", "weight": "114.3" },
{ "date": "2016.01.05", "weight": "114.6" },
{ "date": "2016.01.06", "weight": "114.9" }
]
},
{
"userName": "Wayne",
"weigh-in data": [
{ "date": "2016.02.01", "weight": "120.3" },
{ "date": "2016.02.05", "weight": "123.6" },
{ "date": "2016.02.06", "weight": "123.9" }
]
}
]
}
// etc., more user objects
In my application: a selection of a user is made, an ajax call gets this data, I loop thru it to get only the selected user's weigh-in data, and I'm successfully rendering this data to a table.
Now I'm trying to use the same result in a Dimple chart but Dimple evidently doesn't like my chartData array:
var dataObj = JSON.parse(jsonData);
var usersArray = dataObj.Users;
var chartData = [];
// etc. SNIP
for (var obj of usersArray) {
if (obj.userName === selUser) { // weigh-ins of the selected user only
dataRows.innerHTML = "";
for (var i = 0, j = selUserData.length; i < j; i++) {
var dataDate = selUserData[i].date;
var dataWeight = selUserData[i].weight;
chartData.push('{ "User"' + ': ' + '"'+selUser+'", ' + '"Date":' + ' ' + '"'+dataDate+'", ' + '"Weight":' + ' ' + '"'+dataWeight+'" }');
// SNIP: build rows from the data, load up the table, no problem
dataRows.innerHTML += row;
} // selUserData loop
var svg = dimple.newSvg("#chartContainer", 800, 600);
var chart = new dimple.chart(svg, chartData);
chart.setBounds(60, 30, 505, 305);
var x = chart.addCategoryAxis("x", "Date");
x.addOrderRule("Dates");
var y = chart.addCategoryAxis("y", "Weight");
y.addOrderRule("Weights");
var s = chart.addSeries("weigh-ins", dimple.plot.line);
chart.draw();
... which results in a non-chart. However, if I console.log or alert(chartData) and set the result as chartData, i.e.:
var chartData = [
{ "User": "Wayne", "Date": "2016.02.01", "Weight": "180.3" },
{ "User": "Wayne", "Date": "2016.02.05", "Weight": "123.6" },
{ "User": "Wayne", "Date": "2016.02.06", "Weight": "153.9" }
]
... then I get a chart, ergo my confusion.
Any insight greatly appreciated,
Whiskey
You're pushing the JSON into your array as strings not objects, it should be:
chartData.push({ "User": selUser, "Date": dataDate, "Weight": dataWeight });
Which has the added benefit of being much easier to read!

Push Unique Objects to JavaScript Array

How do I push an object into an specified array that only updates that array? My code pushes an object and updates all arrays, not just the specified one.
Here is the structure of the data:
{
"d": {
"results": [
{
"Id": 1,
"cost": "3",
"item": "Project 1",
"fiscalyear": "2014",
"reportmonth": "July"
}
]
}
}
Here is a sample of the desired, wanted results:
{
"Project 1": [
{
"date": "31-Jul-14",
"rating": "3"
},
{
"date": "31-Aug-14",
"rating": "4"
}
],
"Project 2": [
{
"date": "31-Jul-14",
"rating": "2"
}
]
}
This is my attempt:
var results = data.d.results;
var date;
var projectObj = {},
projectValues = {},
project = '';
var cost = '',
costStatus = '';
for (var i = 0, m = results.length; i < m; ++i) {
project = results[i]['item'];
if (!projectObj.hasOwnProperty(project)) {
projectObj[project] = [];
}
// use Moment to get and format date
date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');
// get cost for each unique project
costStatus = results[i]['cost'];
if (costStatus == null || costStatus == 'N/A') {
cost = 'N/A';
}
else {
cost = costStatus;
}
projectValues['rating'] = cost;
projectValues['date'] = date;
projectObj[project].push(projectValues);
}
Here is a Fiddle with the undesired, unwanted results:
https://jsfiddle.net/yh2134jn/4/
What am I doing wrong?
That is because You do not empty it new iteration. Try this:
for (var i = 0, m = results.length; i < m; ++i) {
projectValues = {};
project = results[i]['item'];
....
}

Create an object with custom structure in javascript

I need to create an array object with this exact structure:
{"item1": {
0 : {
color:"description1",
width:"description2",
height:"description3"
}
1 : {
color:"description1",
width:"description2",
height:"description3"
}
//and so on
},
"item2": {
0 : {
color:"description1",
width:"description2",
height:"description3"
}
//and so on
}
//and so on
}
Estatically works fine. Now, I want to make it dinamically. So, the main question is... How can I loop the data while constructing the object at the same time?
This is an example of the incoming object I work from:
[
{
"uid": 1,
"legendname": "item1",
"rows": [
{
"uid": 0,
"color": "482400",
"width": "482400",
"height": "25"
},
{
"uid": 1,
"color": "587898",
"width": "789658",
"height": "30"
}
]
}
{
"uid": 2,
"legendname": "item2",
"rows": [
{
"uid": 0,
"color": "482400",
"width": "482400",
"height": "25"
}
]
}
]
How can I loop the data while constructing the object at the same time?
Is not clear. But if you want to create a new structure based on the incoming one, you can use this:
// ar = your incoming object
// b_obj = your result
var b_obj = {}
for (var i = 0; i < ar.length; i++)
{
item = ar[i];
b_item = {};
for (var i_row = 0; i_row < item.rows.length; i_row++)
{
var row = {};
row.color = item.rows[i_row].color;
row.width = item.rows[i_row].width;
row.height = item.rows[i_row].height;
b_item[i_row] = row;
}
b_obj[item.legendname] = b_item;
}

Categories