Requesting embedded JSON data for D3 - html

For reasons I won't bore you with, ALL elements of my webpage must be embedded into one file.
Between the HTML header tags, I have valid JSON data declared:
<script type="application/json" id="data">
"name": "flare", "children":[{"name": "thing1", ... }]
</script>
Previously this data was written to a JSON file which was referenced by my D3 bar chart scripts as follows:
d3.json("data/file.json", function(root) {
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
});
I have been able to pass the embedded JSON to an object after following this thread:
Best practice for embedding arbitrary JSON in the DOM?
How can I now successfully pass this object to the D3 bar chart?

Parsing the embedded JSON object was the hard part, so you've basically got this one figured out. Once you have the embedded JSON parsed and passed to an Object, you can just start using that Object.
Building off of your example, say you had this JSON data embedded in your page:
<script type="application/json" id="data">
{"name": "flare", "children":[{"name": "thing1", ... }]}
</script>
Then instead of using
d3.json("data/file.json", function(root) {
...
}
just extract the body of the function you were using, and load the JSON object at the top:
var root = JSON.parse(document.getElementById('data').innerHTML);
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
...

The method described in the question you've linked to will work. Just call the variable whatever you're using in your D3 code, e.g.
var root = JSON.parse(document.getElementById('data').innerHTML);

Related

Angularjs ng-grid using Grails JSON data

Angular ng-grid data binding question
I have a Groovy/Grails application that has a domain “Grid” class for which I have registered a custom “marshaller” to produce the JSON that I can use for an Angularjs ng-grid..
Say “grid” is and instance of the Grid class,
“grid as JSON” produces the desired JSON.
I have a Grails/groovy controller that loads the data and returns the JSON:
def index() {
def grid = Grid.first()
grid as JSON
}
But I don’t know how to get this JSON data into the ng-grid in my GSP:
<body ng-controller="MyCtrl">
<script>
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.gridOptions = ${grid}; // NEED HELP HERE !
});
</script>
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
I don't know how to get the data into $scope.gridOptions. When I look at what is being generated with firebug, I see $scope.gridOptions is
{"columnDefs":[{"field": ...
which is the encoded JSON data. (The quotation marks are encoded). What is the best way to pass JSON data between a Grails back end and ng-grid in a JSP?
Thank you for the suggestion Sridhar, I started looking for ways to un-escape JSON within GSP, and I found the answer here:
how-to-render-json-properly-without-escaping-quotes-inside-a-gsp-script-tag
I need to use the g:applyCodec tag in my GSP:
<g:applyCodec encodeAs="none">
$scope.gridOptions = ${grid};
</g:applyCodec>

Uson jsTree with custom JSON structure

I've been searching for ways to do this, but I'm missing something.
I have a custom JSON object, which can basically have any structure, and I want to use this with jsTree. I've found a corresponding plugin here, that claims to have a _parse_json function to transform a custom JSON object to the format that jsTree requires, but for the life of me I can't figure out how to call that plugin. It seems to be included in the version of jsTree that I'm using (1.0rc3).
There is a usage of UIMTreeProcessor I've found, that consists of parsing the XML and calling jsTree like so:
$.jstree._themes = "Content/jstreethemes/";
this.treeEl.jstree({
"json_data" : {
"data":data,
"progressive_render":"true"
},
"plugins" : [ "themes", "ui", "json_data" ],
"core": { "animation": 0 }
});
Now, instead of UIMTreeProcessor parsing the XML and populating data, I want to call $.json_data._parse_json(), but I keep getting errors that this function doesn't exist.
Can anyone show me an example? Thank you kindly.

Parse Json to use in a dojo widget?

I am newbie to dojo and json. I am trying to Query the server to get data as json and parse the result and use html template in a widget to display.
To test it I tried this.
require(["dojo/request", "dojo/dom", "dojo/dom-construct","dojo/_base/array", "my/widgets/", "dojo/domReady!"],
function(request, dom,domConst, arrayUtil, support){
// Load up our authors
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(LinksMap){
// Get a reference to our container
arrayUtil.forEach(LinksMap, function(List){
// Create our widget and place it
console.debug(LinksMap);
//var widget = new support(author).placeAt(authorContainer);
Not sure if I am doing it right. Is there anything I am misssing. I am following the example as provided here and building on it.
I think from the comments on your post you want to modified the deferred handling function to be
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function(jsonResults){
console.log(jsonResults.Result)
});
The json you posted is an object with a property Result. The Result property contains an array of objects. Those objects then contain a property LinksMap which holds another object.

calling JSON webservice & using html

I've been using XML a lot lately but now I'm practicing with some JSON.
What I am trying to do is make a button and text box - so the user can type in a zip code and it will get the info for that zip code...
Using JSON from geonames.org
It's frustrating me trying to figure this out, I've found it easy when I was making my own files with XML but now I am trying to use an actual website and JSON.
Please show me how to do this! Would appreciate it! Thanks.
First of all HTML cannot process a json response from a server. You can send a get or post in json format to a server and get a json response back but you need something other than HTML to process that JSON message. Browsers can format and display XML but not JSON (they just display it as a string). The easiest way to do that in a browser is use JavaScript. For this I would recommend using the jquery library.
http://jquery.com
Here's an example of some jquery I used recently to process a returned JSON string.
$(document).ready(function() {
$(".img a").on("click", function(event) {
event.preventDefault();
var item;
if ((item= $(this).attr( 'href' ))=="saved") return false;
$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");
var action ="add";
jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
var result=data.result;
if (result=="saved") {
self.html("<div>Saved</div>");
self.attr("href","saved");
}
}, "json")
.error(function() {
alert("error: unable to contact web service");
});
});
});
The returned JSON string from this request is { result: saved }. So as you can see you access the associated array as part of the data object. In my case data.result provided me with the value of result from the json string.
Note my example is for using an anchor tag to pass a value to send in the webservice call. In your case you will need to use a form.
If you're using jeoquery then just look at the html source of UI sample. It's showing the same autocomplete box that you might be trying to implement no custom code to write to parse returned JSON. Below code should work for you:
<input class="input-large" id="city" type="text"/>
$("#city").jeoCityAutoComplete();

Converting velocity response to JSON

I am using struts 2 and velocity templates to generate JSON response.
Now the catch is the response is not generated using some velocity JSON plugin
it's just a String that comes out once velocity is done with its parsing and rendering of
response, and on client side I do eval to get the response from string to JSON.
What I really need is some solution on velocity's or struts' side where, once the result is
generated by velocity, the framework should call my API where I can convert the response output of vm file into JSON using my own logic. How do achieve this?
For example:
On browser using JavaScript I have designed a tree widget that I use for displaying comments in tree structure.
Say user clicks on comments button.
My UI widget will fire an AJAX to get data for comments.
This request is intercepted by STRUTS 2 framework.
It will call, say, getComments() action API and will populate an arrayList with comment object say cmt.
Now the response is handled by a velocity template(*.vm).
Now in vm I am writing code like this:
{ "CommentsData" : [
#set($sep="")
#foreach($c in $cmt)
$sep
{
"commentText" : $c.getText()
}
#set($sep=",")
#end
}
Now the final response may turn out like this:
{ "CommentsData" : [
{
"commentText" : "This is comment 1"
},
{
"commentText" : "This is comment 2"
},
{
"commentText" : "This is comment 3"
},
{
"commentText" : "This is comment 4"
}`
]
}
Now this may look like JSON, but its not strict JSON; I mean if I miss
some , somewhere then on client side in JavaScript my eval might fail or JSON.parse()
will fail, but on velocity template I have now clue if JSON is malformed.
So once the above velocity template is generated I need some control, where I can write some Java code to do some validations on the response.
I see that my approach to use velocity template to generate JSON output (actully a String that looks like JSON) may be wrong. But still I need to handle the response of every velocity template I have written.
Not sure how you are using velocity. We don't use velocity when outputting JSON; we just create a JSON convertible object and output it directly from controllers using response.write(jsonObject.toJson()). This way, proper JSON is always generated.