http://bl.ocks.org/mbostock/4339083 am using this
instead of d3.json("/d/4063550/flare.json", function(error, flare) {
how do i make it use the json file within the html, like say i have
var jsonData = [{
"name": "A",
"children": [
{"name": "A1", "children": [{"name": "A12"},{"name": "A13"},{"name": "A14"}] },
{"name": "A2", "children": [{"name": "A22"},{"name": "A23"},{"name": "A24"}] }
]
}];
and i want to use this instead of an external json file, how do i achieve this ?
Solution:
1.you can assign the JSON data to variable name then You can build the tree layout
2.use one function to get the JSON data
Fiddle for 1 solution
Fiddle for 2 solution
var root = getData(),
nodes = cluster.nodes(root),
links = cluster.links(nodes);
Related
I have a JSON file that contains an array of objects, for example:
[
{"name": "Timothy", "age": 14},
{....},
{....},
...
]
I want to create an array, e.g. people, and store basically the exact same information contained in the JSON file. In other words, I want to store that array itself inside the people array I just declared. How could I do this?
In your case try to use spread operator:
import people from './people.json';
const myPeople = [
{"name": "Timothy", "age": 14},
{...},
{...}
];
people.people = [...myPeople];
people.json file
{
"name": "Test",
"people": []
}
I am new to AngularJs. I am having problem in appending options to select boxes created by javascript. Following is my code.
var inputElements = $('<div><label style="float:left;">' + i + '</label><select ng-model="object" class="form-control sel" style="width:300px; float:right; margin-right:75px;"> <option>select</option></select></div></br></br>');
var temp = $compile(inputElements)($scope);
$('#projOrder').append(temp);
$scope.object = object;
//for(var opt=0; opt<selOptLabels.length; opt++) {
$('.sel').append('<option ng-repeat="obj in object" value="'+
{{obj.value}}+'">'+{{obj.value}}+'</option>');
I am getting this error:- SyntaxError: invalid property id
Hi, I am posting json example. This is just a small part of json in my case.
"ProjectOrder": {
"Connect direct required": {
"value": "N",
"id": "STR_15523_62"
},
"Cores": {
"value": ".5",
"id": "NUM_15523_50"
},
"Permanent data in GB": {
"value": "100",
"id": "NUM_15523_56"
},
"Description": {
"value": "AZBNL azbngb",
"id": "STR_15523_2"
},
"Order Id": {
"value": "15523",
"id": "INT_15523_96"
},
"Project cost center": {
"value": "N",
"id": "STR_15523_66"
},
"Project debitor": {
"value": "N",
"id": "STR_15523_64"
},
"Project OE": {
"value": "N",
"id": "STR_15523_57"
},
"Project SITE": {
"value": "N",
"id": "STR_15523_59"
},
"Project Status": {
"value": "RFC",
"id": "STR_15523_54",
"dropdown": [
{
"value": "IW",
"label": "In Work"
},
{
"value": "RFC",
"label": "Ready for Creation"
},
{
"value": "CR",
"label": "Created"
},
{
"value": "FC",
"label": "Failed"
}
]
},
"Project Type (paas, miner)": {
"value": "paas",
"id": "STR_15523_37",
"dropdown": [
{
"value": "paas",
"label": "PaaS Project"
},
{
"value": "miner",
"label": "Miner Project"
}
]
},
"WORK data in GB": {
"value": "100",
"id": "NUM_15523_55"
}
}
Now I have to create input fields and dropdown menus(if there is a dropdown menu) with json data
You really should not be hand-constructing HTML like that. It's best if you use a template and let the template engine handle the heavy lifting.
I also noticed that you're using object as the ng-model. Instead you should have a separate variable which will hold the selected value.
Here's a better way of doing this--in an .html file:
<div ng-repeat="object in listOfObjects"
<label style="float: left">{{ $index }}</label>
<select ng-model="selectedValues[$index]" class="form-control sel"
style="width:300px; float:right; margin-right:75px;"
ng-options="obj.value for obj in object"></select>
</div>
Then in whatever controller you have set up in JavaScript:
// this will be the list of selected values
$scope.selectedValues = new Array(list.length);
// this would be the array that each `object` is part of
$scope.listOfObjects = list;
This isn't the most elegant solution, but basically what I've done is construct an array that is the same length as the list of objects. Angular templates have a special variable $index when you're in an ng-repeat which tracks the current index of the array you're looping through.
So when a user changes the selected value of the 3rd select box (index 2), $scope.selectedValues[2] would be set to the selected option.
EDIT: on transforming the JSON to an array:
var list = Object.keys(json).map(function(jsonKey) {
return {
name: jsonKey,
label: json[jsonKey].label,
value: json[jsonKey].value
};
});`
So.. there are a number of reasons why that won't work. The provided code wouldn't even work because of the template brackets that you are trying to append to your html string...
$('.sel').append('<option ng-repeat="obj in object" value="' +{{obj.value}}+'">'+{{obj.value}}+'</option>');
Is there a reason that you are trying build your markup in js?
It's also advised not to use jquery inside angular controllers. If you have jquery loaded the jQuery object is available through angular.element, otherwise angular uses jQuery light.
Rather than enumerate on the other issues here, I put together this basic example of how a select works in Angular
https://codepen.io/parallaxisjones/pen/BRKebV
Also, you should consult the angular documentation before posting questions to stack overflow. The docs provide a pretty clear example of how to use ng-repeat in a select. https://docs.angularjs.org/api/ng/directive/select
EDIT: I updated my codepen with an example of fetching JSON data with an HTTP GET request
EDIT: updated codepen with provided data example, iterating over object with (key, value) in json syntax in ng-repeat
I'd like to use a csv file instead of a json file in this example:
https://bl.ocks.org/mbostock/4339083
Any idea for loading a csv instead of a json file?
The problem here is way more complicated than it seems, and I suggest you that you leave the data file as JSON. The reason is this: the JSON file in your question contains nested data.
Here is an explanation:
Apparently, the only difference between loading a CSV file and loading a JSON file is the request function:
d3.json("data.json", function(data){
//code here
)}
... for a JSON and:
d3.csv("data.csv", function(data){
//code here
)}
... for a CSV.
But there is more. Besides the fact that d3.csv accepts an accessor (row) function and d3.json does not, d3.json loads the data as it is. On the other hand, d3.csv parses the file according to the columns, creating an array of objects.
Thus, if you have this CSV:
city,population,area
New York,3400,210
Melbourne,1200,350
Tokyo,5200,125
Paris,800,70
... it will be parsed to this array:
[{
"city": "New York",
"population": "3400",
"area": "210"
}, {
"city": "Melbourne",
"population": "1200",
"area": "350"
}, {
"city": "Tokyo",
"population": "5200",
"area": "125"
}, {
"city": "Paris",
"population": "800",
"area": "70"
}]
And here comes the problem: As you can see, there is no nested data in the array created by d3.csv. All the objects are side by side in the array.
However, the data object in Bostock's code you linked is way different:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 3938},
{"name": "CommunityStructure", "size": 3812},
//...
As you can see, you have arrays inside objects inside arrays inside objects...
So, to recreate the nested JSON in your question, you'll have to create an additional column, specifying who is parent of who and who is child of who:
name,value,parentOf
foo,42,bar
bar,53,baz
...
Then, after parsing this CSV, you'll have to stratify it, using stratify():
var nestedData = d3.stratify()
.id(function(d) { return d.name; })
.parentId(function(d) { return d.parentOf; })
(data);
As you can see, those are complicated steps.
Therefore, as a general rule: if you have nested data as a JSON file, just use d3.json, which loads the data as it is.
You can use d3.csv() instead of d3.json(). See D3's documentation.
I want to convert the data from an Excel file to a JSON file. However, I'm not sure about the design of my JSON code (i.e. is it organized in a proper way in order to process it easily?)
I will use this JSON file with D3.js.
This a small part of my Excel file:
I'd like to convert this data into a JSON file in order to use it with D3.js. This is what I have so far:
So my question is: is this a good design (way) for organizing the data in order to use it with D3.js?
This is a sample output:
Thanks in advance!
This is a somewhat subjective question, but from my experience, there is a better way:
Since you're working in d3, you're probably doing something like this:
d3.selectAll('div')
.data(entities)
.enter()
.append('div')
...
So you want entities to be an array. The question is what are your entities? Is there a view where entities are all the countries in the world? Is there a view where entities are all the countries plus all the regions plus the whole world? Or, are all the views going to be simply all the countries in a selected region, not including the region itself?
The unless the JSON structure you're proposing matches the combinations of entities that you plan to display, your code will have to do a bunch of concat'ing and/or filtering of arrays in order to get a single entities array that you can bind to. Maybe that's ok, but it will create some unnecessary amount of coupling between your code and the structure of the data.
From my experience, it turns out that the most flexible way (and also probably the simplest in terms of coding) is to keep the hierarchy flat, like it is in the excel file. So, instead of encoding regions into the hierarchy, just have them in a single, flat array like so:
{
"immigration": [
{
"name": "All Countries"
"values: [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Africa"
"values: [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Eastern Africa"
"continent": "Africa"
"values": [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Burundi"
"continent": "Africa"
"region": "East Africa"
"values": [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Djibouti"
"continent": "Africa"
"region": "East Africa"
"values": [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
...
]
}
Note that even though the array is flat, there is still a hierarchy here -- the region and sub-region properties.
You'll have to do a bit of filtering to extract just the countries/regions you want to show. But that's simpler than traversing the hierarchy you're proposing:
var africanEntities = data.immigration.filter(function(country) {
return country.continent == "Africa";
}); // Includes the region "East Africa"
var justCountries = data.immigration.filter(function(country) {
return country.continent != null && country.region != null;
});
Also, d3 has the awesome d3.nest(), which lets you turn this flat data into hierarchical one with little effort:
var countriesByContinent = d3.nest()
.key(function(d) { return d.continent; })
.map(data.immigration);
var africanEntities = countriesByContinent['Africa'];
Hope that helps....
I have a hierarchical structure data, and can be treat as a tree structure.
First
I need to split this hierarchical tree into sub-tree and get all the sub-trees.
The function below is how I did, it works well
var hierarchObjects = [];
traverseNodes(root);
function traverseNodes(root){
hierarchObjects.push(root);
for(var i=0; i<root.children.length; ++i)
{
traverseNodes(root.children[i]);
}
}
Second
I need to group the nodes for each level of a subtree, in Array hierarchObjects. And the depth of the sub-tree is different.
For example,
put nodes of a sub-tree of level1 in array Level1.
put nodes of a sub-tree of level2 in array Level2.
So What should I do for Second process?
Is there a more efficient way for all the process?
Because My dataset is a bit big, and there are about 1300 sub-trees, I need to find an efficient way?
My dataset is a tree structure: http://www.csee.umbc.edu/~yongnan/untitled/pathwayHierarchy.json
You can see it is a parent-----children structure tree.
For this tree I use step 1 to split into sub-trees.
For each sub-tree, example as below:
1
{
"dbId": "111461",
"name": "Cytochrome c-mediated apoptotic response",
"children": [
{
"dbId": "111458",
"name": "Formation of apoptosome",
"children": [],
"size": 1
},
{
"dbId": "111459",
"name": "Activation of caspases through apoptosome-mediated cleavage",
"children": [],
"size": 1
}
]
}
for this sub-tree, it just has two children for level1, so the return array should be [[Formation of apoptosome,Activation of caspases through apoptosome-mediated cleavage ]]
2
{
"dbId": "111471",
"name": "Apoptotic factor-mediated response",
"children": [
{
"dbId": "111461",
"name": "Cytochrome c-mediated apoptotic response",
"children": [
{
"dbId": "111458",
"name": "Formation of apoptosome",
"children": [],
"size": 1
},
{
"dbId": "111459",
"name": "Activation of caspases through apoptosome-mediated cleavage",
"children": [],
"size": 1
}
]
},
{
"dbId": "111469",
"name": "SMAC-mediated apoptotic response",
"children": [
{
"dbId": "111463",
"name": "SMAC binds to IAPs ",
"children": [],
"size": 1
},
{
"dbId": "111464",
"name": "SMAC-mediated dissociation of IAPcaspase complexes ",
"children": [],
"size": 1
}
]
}
]
}
for this dataset, the result could be
[
[Cytochrome c-mediated apoptotic response,SMAC-mediated apoptotic response],
[Formation of apoptosome,Activation of caspases through apoptosome-mediated cleavage,SMAC binds to IAPs, SMAC-mediated dissociation of IAPcaspase complexes]
]
Now, I am trying to use Breadth first algorithm to do the Second step. I know the efficient is not very good.
Thanks!
This should do the trick, and unless you are handling around 1m nodes or very deep trees, should be pretty fast:
var data={
//your data
}
var arr=[]; // array that holds an array of names for each sublevel
function traverse(data, level){
if(arr[level]==undefined) arr[level]=[]; // if its the first time reaching this sub-level, create array
arr[level].push(data.name); // push the name in the sub-level array
for(var index=0;index<data.children.length;index++){ // for each node in children
traverse(data.children[index], level+1); // travel the node, increasing the current sub-level
}
}
traverse(data, 0); // start recursive function
console.log(arr)
Full fiddle: http://jsfiddle.net/juvian/fmhrpdbf/1/