How can I select specific JSON attributes for jstree? - json

I have implemented a jstree which uses the json_data plugin to retrieve json data with ajax from a server. The json attributed for one node look like:
{"data":"1","uri":"http://www.abc.com/1"}
My problem now is, how can I save these attributes in the jstree nodes? I know that there's a "data" option looking like this:
"data" : function (n) {
return { id : n.attr ? n.attr("id") : 0
};
I'm relativley new to jquery and jstree and I don't know how I can use the data option to
assign these attributed to the nodes. This is important because I have to get the JSON data from the tree after it was changed (using create, rename, remove, dnd operations) and therefore the JSON has to look like the one which was initially requested from the server through ajax.
Can somebody help me?
Have a nice day!

You create your json jsTree structure + data + all attributes on server side.
jsTree receives json and displays it. There might be some way how to tweak the data in javascript once you received it. Make it simple and do it on server side.
Below is bit of my server side script in ruby that creates json structure. Note that year, month etc are custom attributes.
hash_tmp = {
"data" => dir,
"attr" => { "group" => group,
"build_name" => build_name,
"year" => year_tmp,
"month" => month_tmp,
"daytime" => daytime,
"action" => action,
"rel" => type,
},
"state" => state,
"children" => ""
}

Related

handling a well-formed JSON file of an array of objects

A JSON string string passes the jsonlint test.
response = [
{
"article" : {
"info" : {
"initial" : {
"articleIds" : [
"7461221587662919569"
],
}
},
"text" : "where they would 'transfer to' next.",
"lang" : "en",
}
},
{
"article" : {
"info" : {
"initial" : {
"articleIds" : [
"6613144915874808065"
],
}
},
"text" : "produto regional.",
"lang" : "pt"
}
}
]
However, after processing
require 'json'
file = File.read('/Users/main/jugg//article_samples.js')
data_hash = JSON.parse(file)
One is left with an array, whereas more frequently a hash with a name labels a subsequent array, where one works with that nomenclature such as response['data']
But in this case the array is not accessible via response[0]. How can this be considered as an array in order to process each individual element collection.each do |member|?
A curiosity: data_hash.class => NilClass
The response = ... code from article_samples.js is JavaScript, not JSON. This initializes a variable named response with a JavaScript array.
To use this as JSON, then rename the file to article_samples.json and remove response = from the file. The first line should start with [.
Now your second block of code should work just fine as long as the article_samples.json file is in the correct path.
On a side note, I suggest that you find a way to make the path more flexible. The way you have it currently hard coded is tied directly to your current machine's file system. This won't work if you want to run this code from another machine because the folder /Users/main/jugg probalby won't exist.
If this is a web server with ruby on rails, then one solution is to create an environment variable with the path where this file is stored.

Using Laravel, is there a way to run validation on one ajax call with data for multiple models?

Assuming one were to post multiple data sets of one model at the time through JSON, it is possible to insert these using Eloquent's Model::create() function. However in my case I'll also need to validate this data.
The Validator only takes a Request object as input, and as far as I've seen I can't create a new Request instance with only one model.
Assuming this would be the input data (JSON), and index is the value for the browser to know what data belongs to an what item (as they have no unique ID assigned at the point of creation)
[
{
"index" : 1,
"name" : "Item 1",
"value" : "Some description"
},
{
"index" : 2,
"name" : "Item 2",
"value" : "Something to describe item 2"
},
(and so on)
]
Every object in the root array needs to be ran through the same validator. The rules of it are defined in Model::$rules (public static array).
Would there be a way to run the validator against every item, and possibly capture the errors per item?
You can utilize Validator for manual validation:
...
use Validator;
...
$validator = Validator::make(
json_decode($data, true), // where $data contains your JSON data string
[
// List your rules here using wildcard syntax.
'*.index' => 'required|integer',
'*.name' => 'required|min:2',
...
],
[
// Array of messages for validation errors.
...
],
[
// Array of attribute titles for validation errors.
...
]
);
if ($validator->fails()) {
// Validation failed.
// $validator->errors() will return MessageBag with what went wrong.
...
}
You can read more about validating arrays here.

TypeScript / Angular 2 creating a dynamic object deserializer

So I am coming from a background of C# where I can do things in a dynamic and reflective way and I am trying to apply that to a TypeScript class I am working on writing.
Some background, I am converting an application to a web app and the backend developer doesn't want to change the backend at all to accommodate Json very well. So he is going to be sending me back Json that looks like so:
{
Columns: [
{
"ColumnName": "ClientPK",
"Label": "Client",
"DataType": "int",
"Length": 0,
"AllowNull": true,
"Format": "",
"IsReadOnly": true,
"IsDateOnly": null
}
],
Rows:[
0
]
}
I am looking to write an Angular class that extends Response that will have a special method called JsonMinimal which will understand this data and return an object for me.
import { Response } from "#angular/http";
export class ServerSource
{
SourceName: string;
MoreItems: boolean;
Error: string;
ExtendedProperties: ExtendedProperty[];
Columns: Column[];
}
export class ServerSourceResponse extends Response
{
JsonMinimal() : any
{
return null; //Something that will be a blank any type that when returned I can perform `object as FinalObject` syntax
}
}
I know StackOverflow isn't for asking for complete solutions to problems so I am only asking what is one example taking this example data and creating a dynamic response that TypeScript isn't going to yell at me for. I don't know what to do here, this developer has thousands of server-side methods and all of them return strings, in the form of a JSON or XML output. I am basically looking for a way to take his column data and combine it with the proper row data and then have a bigger object that holds a bunch of these combined object.
A usage case here after that data has been mapped to a basic object would be something like this.
Example:
var data = result.JsonMinimal() as LoginResponse; <-- Which will map to this object correctly if all the data is there in a base object.
var pk = data.ClientPK.Value;
I'm not exactly sure I understand, but you may want to try a simple approach first. Angular's http get method returns an observable that can automatically map the response to an object or an array of objects. It is also powerful enough to perform some custom mapping/transformation. You may want to look at that first.
Here is an example:
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
Here I'm mapping a json response to an array of Product objects I've defined with an IProduct interface. Since this is just a "lambda" type function, I could add any amount of code here to transform data.

working with JSON data, trying to parse nested data

I just working with JSON data and am playing around with jQuery and Ajax requests. Pretty basic stuff, but here's my problem.
I have a basic data set which I was using for time tracking. I know how to parse the simple JSON data like this:
{
"end" : "1/18/2011",
"start" : "1/18/2011",
"task" : "Code Review",
},
It's the more complicated stuff I'm trying to parse like this where I'm trying to pull the "time" data out.
{
"end" : "1/17/2011",
"start" : "1/17/2011",
"task" : "Exclusive Brands",
"time" : {
"analysis" : 4,
"documentation" : 3,
"meetings" : 2
}
This is the code for the script I've been using to parse the simple data:
$(function() {
$('.load').click(function(){
$.getJSON("data.js",function(data){
$.each(data.timesheet, function(i,data){
var div_data ="<div class='box'>"+data.start+" "+data.task+"</div>";
$(div_data).appendTo("#time-tracking");
});
}
);
return false;
});
});
My question is what's the format to parse the time data, or what's the best way to parse the information nested inside the time element?
Any help will be greatly appreciated.
A JSON string will be parsed into an object. When parsed, the time is the key of one object. You could retrieve the value of this object through the dot operator (.).
data = JSON.parse('{"end":"1/17/2011", "start":"1/17/2011", "task":"Exclusive Brands", "time": {"analysis":4, "documentation":3, "meetings":2 } }')
// => obj
data.time.analysis
// => 4
In your case similarly you could use the data.time.meetings to access your data from remote server.
Unless I am terribly mistaken, since jquery already converted data into a javascript for you, you should be able to access time as if it was a javascript object like so:
var analysis = data.time.analysis;
var documentation = data.time.documentation;
var meetings = data.time.meetings;
etc...

Accessing hashes in Perl templates

How do you access variables in a hash when using Perl's HTML::Template module?
I'm building the following hash in my Perl code:
# Load success/error flash messages
if ($query->param("submit")) {
$template->param(
FLASH => {
CLASS => "success",
MESSAGE => "Your cart has been successfully updated!"
}
);
}
I'd like to access these variables in my template. To access a regular variable, you do:
<TMPL_VAR NAME=FLASH>
How might I access FLASH['CLASS'] in my template?
Access with a . (dot)
FLASH.CLASS
There's nothing in the documentation that indicates you can set a parameter as a hashref. The closest to what you want to do is to put the hashref in an arrayref:
$template->param(
FLASH => [ {
CLASS => "success",
MESSAGE => "Your cart has been successfully updated!"
} ]
);
Then you can access it as:
<TMPL_LOOP NAME=FLASH>
<TMPL_VAR NAME=CLASS>
<TMPL_VAR NAME=MESSAGE>
</TMPL_LOOP>
But having an array with a single element might be overkill. An alternative is to get rid of the hashref and flatten the structure:
$template->param(
FLASH.CLASS => "success",
FLASH.MESSAGE => "Your cart has been successfully updated!"
);
...
<TMPL_VAR NAME=FLASH.CLASS>
<TMPL_VAR NAME=FLASH.MESSAGE>
HTML::Template always needs a hash of arrays of hash of arrays and so on.
If you have an arbitrary data structure you might want to try HTML::Template::Compiled where you can use the dot syntax (disclaimer: I'm the author)
There is also HTML::Template::Plugin::Dot but I have never tested it and it seems to be a bit more limited.