D3 collapsible trees without flare.json - javascript

I am trying to integrate a collapsible tree with a visualization tool :
http://bl.ocks.org/robschmuecker/7880033
Can someone please tell me how to make this code run without a flare.json file. I have the data in json format and I need to use that json output to make this code run. The code I have that converts a string into a json format is as follows:
<html>
<body>
<script>
//example dat
var str = "Charles Johnson\t4184\nCharles Johnson-Donald Williams\t8385\nCharles Johnson-Donald Williams-Daniel Fertig\t428\nCharles Johnson-Donald Williams-Daniel Fertig-Lino Walling\t1091\nCharles Johnson-Donald Williams-Daniel Fertig-Lino Walling-Jim Cooke\t318";
var lines = str.split("\n");
var name_ = lines[0].split("\t")[0];
var val_ = lines[0].split("\t")[1];
//alert(val_);
var obj = {name: name_,
children: [],
value: val_};
//process all lines
for (var i=1;i<lines.length;i++) {
var addr = lines[i].split("\t")[0].split("-");
var val = lines[i].split("\t")[1];
//alert(val);
var local_obj = obj;
var recursive_obj;
//alert(addr.length);
for (var j=1;j<addr.length;j++) {
recursive_obj = null;
for (var k=0;k<local_obj.children.length;k++) { //Doest get used for first instance
if (local_obj.children[k].name==addr[j]) {
recursive_obj=local_obj.children[k];
}
}
if (recursive_obj==null) {
recursive_obj = {name: addr[j],
children: [],
value: null
};
local_obj.children.push(recursive_obj);
}
local_obj=recursive_obj;
}
recursive_obj.value=val;
}
//print a json result
alert(JSON.stringify(obj));
</script>
</body>
</html>
This code converts the string into Json Format. Can someone please help me out in using this code instead of
treeJSON = d3.json("flare.json", function(error, treeData){}
and making the collapsible tree run. I would be very grateful if someone can assist me with this. Thank you :)
Best Regards
Mohd
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="try.js"></script>
<body>
<div id="tree-container"></div>
</body>
</html>

Right now you have obj, which is already an object, similar to what treeData needs to be inside the callback to the d3.json function. You can take everything out of that function, converting from this:
d3.json("flare.json", function(error, treeData){
//Do some stuff with treeData
})
to this:
var treeData = obj;
//Do some stuff with treeData;
Working fiddle: fiddle

Related

Access Json-Object that is not stored inside a variable [duplicate]

I am trying to access the content in eventbrite emails that I receive but the html code doesn't have an ID associated to the JSON-LD script. So is there a way to still access this data? If so, how?
Is it possible to perhaps attach a temporary id to the JSON-LD script tag so that I can access the data? If so, how?
You can get all JSON-LD blocks with
document.querySelectorAll('script[type="application/ld+json"]');
or just the first one with
document.querySelector('script[type="application/ld+json"]');
Here's a full example:
var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
document.getElementById('result').innerText = jsonld.endDate;
<html>
<head>
<script type="application/ld+json">
{
"#context": "http://schema.org",
"#type": "Event",
"name": "A random event",
"startDate": "2013-09-14T21:30",
"endDate": "2013-09-14T21:30"
}
</script>
</head>
<body>
<p>The end date is: <strong id="result"></strong></p>
</body>
</html>
function myFunction() {
var todayDate = new Date();
var label = GmailApp.getUserLabelByName("eventbrite");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
threads[i].getMessages()[i].getBody().forEach(
var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);
document.getElementById('result').innerText = jsonld.endDate;
if (jsonld.endDate > todayDate){
threads[i].markUnread();
}
)
}
}

How to parse date format, without access to source code

{$userinfo.create_account_date}
This returns me date in the following format: Oct-3-2017
I want to parse it to: DD/MM/YYY (03/10/2017)
The source code is encrypted. Is there a way to parse it through front-end only?
Front-end, assuming JavaScript. In most simple style.
function reformatDate(datumStr) {
var monthsArr = [];
monthsArr['Jan'] = '01';
// add missing months here
monthsArr['Oct'] = '10';
var dArr = datumStr.split('-');
return [dArr[1], monthsArr[dArr[0]], dArr[2]].join('/');
}
console.log(reformatDate('Oct-3-2017'));
Output:
3/10/2017
Addition to Karen's comment below.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function reformatDate(datumStr) {
var monthsArr = [];
monthsArr['Jan'] = '01';
// add missing months here
monthsArr['Oct'] = '10';
var dArr = datumStr.split('-');
return [dArr[1], monthsArr[dArr[0]], dArr[2]].join('/');
}
function elRfr(idName, datumStr) {
var id = document.getElementById(idName);
id.innerHTML = reformatDate(datumStr);
}
</script>
</head>
<body>
<div id="ourDate"><script type="text/javascript">elRfr('ourDate', 'Oct-3-2017');</script></div>
</body>
</html>
Karen, this is simplified example with just one DIV. In your case you should replace 'Oct-3-2017' with {$userinfo.create_account_date}, I guess.
If I assume correctly that your code is Salesforce Apex code.
Create a new var, initialize the date string as a new Date:
var d = new Date('Oct-3-2017');
Then manipulate it however you want with Date methods.

Need to pass node object created in loop to edges

I am reading in and looping through a json file to create a graph with nodes and edges using a JavaScript library cytoscape, but am having some newbie problems. Here is my pseudo code w/pseudo bugs.
1) Create new node for each node with label 'x'
2) For each edge in edges, create edge with 'source', 'target'.
The problem that I am having is that to create the edge I need to pass each node object as the argument, (sourceNode, targetNode, {weight: 'y'} so something like this will not work
var edge = graph.newEdge({source: graphP.elements.edges[j].data.source},
{target: graphP.elements.edges[j].data.target});
I tried creating an array and writing each new node to it, but I just end up over-writing the value of the variable name and end up with an array of length 1. While all my nodes are created, I need a way to go back and access the nodes in order to create the edges ( and obviously not have them point to themselves).
I am guessing it will be some sort of nodeObject.hasKey[label] and match on that label to retrieve node ID, then create new edge?
I've thought myself in a knot here. Any advice is appreciated. Below is my current code with abbreviated json file read in.
<html>
<head>
<title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>-->
<script/>
$(document).ready(function(){
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/SuperSmallNodes.json',
type: 'GET',
dataType: 'json'
}).done(function(graphP) {
console.log(graphP);
var graph = new Springy.Graph();
for ( i = 0 ; i < graphP.elements.nodes.length ; i++ ) {
var nodeArray = []
var Nlabel1 = graphP.elements.nodes[i].data.label
var Nlabel2 = graphP.elements.nodes[i++].data.label
console.log('Nlabel1')
console.log(Nlabel1)
console.log('Nlabel2')
console.log(Nlabel2)
var NN1 = graph.newNode({label: Nlabel1})
var NN2 = graph.newNode({label: Nlabel2})
nodeArray.push(NN1)
nodeArray.push(NN2)
graph.newEdge(NN1,NN2, {weight: .5})
}
console.log('NODE ARRAY')
console.log(nodeArray)
console.log('WINDOW')
jQuery(function(){
var springy = window.springy = jQuery('#springydemo').springy({
graph: graph,
nodeSelected: function(node){
console.log('Node selected: ' + JSON.stringify(node.data));
}
});
});
});
});
</script>
<div>
<canvas id="springydemo" width="800" height="400" style="border: 1px solid black;"></canvas>
</div>
</body>
</html>
At minimum, I would think you'd want to initialize nodeArray outside of the loop:
var nodeArray = []
for ( i = 0 ; i < graphP.elements.nodes.length ; i++ ) {
As is, the re-initialization in each loop would explain the length of 1.
I apparently got so focused on other problems that I didn't see that I was initializing my array inside the loop. Genius. However, for reference, here is how I was able to pass the sourceNode and targetNode objects to the newEdge function.
<html>
<head>
<title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>-->
<script/>
$(document).ready(function(){
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/SuperSmallNodes.json',
type: 'GET',
dataType: 'json'
}).done(function(graphP) {
console.log(graphP);
var graph = new Springy.Graph();
var nodeArray = []
for ( i = 0 ; i < graphP.elements.nodes.length ; i++ ) {
var Nlabel1 = graphP.elements.nodes[i].data.label
var Nmass = graphP.elements.nodes[i].data.mass
var NN1 = graph.newNode({label: Nlabel1}, {'text-outline-width': Nmass});
nodeArray.push(NN1)
}
console.log(nodeArray)
function getByValue(arr, value) {
for (var n=0; n < nodeArray.length; n++) {
if (arr[n].data.label == value) {
console.log("below should be the object of element")
return arr[n];
}
}
}
function getSourceNode(graphP) {
for (var s=0; s < graphP.elements.edges.length; s++) {
var getSource = graphP.elements.edges[s].data.source
var getTarget = graphP.elements.edges[s].data.target
graph.newEdge(getByValue(nodeArray, getSource),getByValue(nodeArray, getTarget));
}
}
getSourceNode(graphP)
console.log('WINDOW')
jQuery(function(){
var springy = window.springy = jQuery('#springydemo').springy({
graph: graph,
nodeSelected: function(node){
console.log('Node selected: ' + JSON.stringify(node.data));
}
});
});
});
});
</script>
<div>
<canvas id="springydemo" width="800" height="400" style="border: 1px solid black;"></canvas>
</div>
</body>
</html>

Jquery .get not retrieving file

i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>

Grabbing Name attribute of Tags/Tag in Rally

I have been looking at the rally Object model, but I can't figure out how to grab the Name attribute of a Defect's Tag.
I made sure to include Tag and Tags in my fetch statement. I am storing all the defects into an array of objects called defectsNEWDEFECTS[]
I can return a Tag object by doing this:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags;
document.write(tagNEWDEFECTS);
which will return this:
[object Object]
But, I can't seem to get it to return the NAME of the tag.
I tried:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags.Tag.Name;
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tag.Name;
But they all return 'undefined'.
Any ideas how to get the name of a tag? Ultimately, the goal here is to have user-input custom tags that I can flag in my program to do certain things. For example, one tag will be named 'RollOverDefect'.
I need to be able to determine which Defects have a Tag called 'RollOverDefect'
Thanks!
Tags is a collection, so you'll ultimately need a nested loop over the Tags collection attribute to handle this. Once you've nested into an additional loop, you can reference the Tag Name via:
tagNEWDEFECTS = defectsNEWDEFECTS[i].Tags[j].Name;
Hope this is helpful - let us know if that gets the job done.
You may find this example to be useful:
<html>
<head>
<title>App Example: Defects with Tags</title>
<meta name="Name" content="App Example: Defects with Tags" />
<meta name="Version" content="2013.2" />
<meta name="Vendor" content="Rally Labs" />
<script type="text/javascript" src="/apps/1.33/sdk.js?apiVersion=1.43""></script>
<script type="text/javascript">
var table = null;
function defectsWithTagsExample() {
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__'
);
function itemQuery() {
var queryObject = {
key: 'defects',
type: 'Defect',
fetch: 'FormattedID,Name,State,Description,Tags,Name',
query: '(State = "Submitted")'
};
rallyDataSource.findAll(queryObject, populateTable);
}
function populateTable(results) {
if (table) {
table.destroy();
}
var tableDiv = document.getElementById('aDiv');
var config = {
'columnKeys' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnHeaders' : ['FormattedID', 'Name', 'Description', 'State', 'Tags'],
'columnWidths' : ['100px', '400px', '200px', '85px', '300px']
};
table = new rally.sdk.ui.Table(config);
table.addRows(results.defects);
for (i=0;i<results.defects.length;i++) {
myDefect = results.defects[i];
myTags = results.defects[i].Tags;
myTagString = "";
for (j=0;j<myTags.length;j++) {
myTag = myTags[j];
myTagName = myTags[j].Name;
if (j == 0) {
myTagString += myTagName;
} else {
myTagString += ", " + myTagName;
}
}
linkConfig = {item: {FormattedID: myDefect.FormattedID, "_ref" : myDefect._ref}};
defectLink = new rally.sdk.ui.basic.Link(linkConfig);
table.setCell(i, 0, defectLink.renderToHtml());
table.setCell(i, 4, myTagString);
}
table.display(tableDiv);
};
itemQuery();
}
rally.addOnLoad(defectsWithTagsExample);
</script>
</head>
<body>
<div id="aDiv"></div>
</body>
</html>

Categories

Resources