Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model?
Maybe something like kendo.parseData(json, model), which will return array of objects?
I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:
function parse(model, json) {
// I initialize the model with the json data as a quick fix since
// setting the id field doesn't seem to work.
var parsed = new model(json);
var fields = Object.keys(model.fields);
for (var i=0; i<fields.length; i++) {
parsed.set(fields[i], json[fields[i]]);
}
return parsed;
}
Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.
I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.
kendo.data.DataSource.prototype.parse = function (data) {
return this.reader.data(data);
// Note that the original data will be modified. If that is not what you want, change to the following commented line
// return this.reader.data($.extend({}, data));
}
// ...
someGrid.dataSource.parse(myData);
If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.
Related
I am having an issue while cloning objects. I have strategies array to which i am trying to add strategy objects.It works some times while errors with the following error message. Could somebody tell me what the problem could be.
The strategy object consists of objects of objects. In the Add method , I am trying to add Strategy of element zero to the strategy array.
export interface Strategy {
domicile: Domicile;
captiveAssumption: StrategyCaptiveAssumption;
modelingAssumptions: StrategyModelingAssumption;
selectedLinesOfBusiness: SelectedLineOfBusinessInput[];
accountRules: StrategySpecialAccountRules;
minCapitalContribution: StrategyMinCapitalContribution;
results: Results;
}
Converting circular structure to JSON
at JSON.stringify ()
add() {
if (!this.showAddStrategy) {
return;
}
const strategy: Strategy = JSON.parse(JSON.stringify(this.strategies[0]));
this.strategies.push(this.strategies[0]);
this.save.emit();
this._expandLastStrategy();
}
A circular structure is a structure which references itself as a value. JSON.stringify does not support such structures, since it would result in an infinitely-long string.
What you need is a deep cloning function which does not use JSON.stringify. Such implementation can be found here.
I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.
I have a json file that is requested from a server so i can't modify how is sent, but all the data i need is there, so i want to put that data into the charts, the thing is how i can break down the json file, because the relevant data is nested, the structure is
estados(array of object)
id (property)
name (property)
localidades (array of object)
id (property)
name (property)
type1 (object)
type2 (object) etc..
i need to retrieve the id data from the object estados and localidades then especific data one of the objects nested in localidades.
How i can do that? i only know how to go through every nested object by iteration, but decomposing it?
here is a json sample :
http://www.jsoneditoronline.org/?id=9cd4c3af94f14b1cca2d35226794ea78
The Lodash library (Or Underscore, if you prefer) is what you are looking for. You can use it to manipulate your collections any way you want (pretty much). You could potentially do without helper libraries, but it is much easier (and sometimes faster, though browser dependent [ref]) to do it this way.
Here are some examples in the jsFiddle I put together for a demo. Some example of how to access particular property of an object inside an array of objects:
$scope.findObjects = function () {
var estado = _.find($scope.allJson, {
"idEstado": $scope.idToSearch
});
$scope.exampleOutput = _.filter(estado.localidades, function (item) {
return item.demanda && (item.demanda.ata > 5);
});
};
I often work with large JavaScript objects and instead of manually opening and closing "branches", I would like to simply search for a particular string and show any key or value that matches.
Sort of like "grepping" for a keyword in a JavaScript object. Is this possible (especially in Chrome Dev Tool)?
Unfortunately I was hoping I could at least try the JSON.stringify() trick and then search on the raw JSON in a text editor, but I get the following error:
Uncaught TypeError: Converting circular structure to JSON
You can look at the object's keys and match against them:
function grepKeys(o, query){
var ret = {};
Object.keys(o).filter(function(key){
return key.includes(query);
}).forEach(function(key){ // can reduce instead
ret[key] = o[key]; // copy over
});
return ret;
}
Which'd let you return a partial object with all the keys that contain the string you specified. Note that this will not show any prototype keys but can be easily extended to allow it (by using a for... in instead of an Object.keys or by using recursion):
var o = grepKeys({buzz:5, fuzz:3, foo:4}, "zz");
o; // Object {buzz: 5, fuzz: 3}
this is my json format
({"message":{"success":true,"result":[{"lead_no":"LEA13","lastname":"Developer","firstname":"PHP","company":"Dummies","email":"nandhajj#gmail.com","id":"10x132"},{"lead_no":"LEA14","lastname":"Venu","firstname":"Yatagiri","company":"Rsalesarm","email":"veve#jajs.com","id":"10x133"},{"lead_no":"LEA4","lastname":"Jones","firstname":"Barbara","company":"Vtigercrm inc","email":"barbara_jones#company.com","id":"10x35"},{"lead_no":"LEA1","lastname":"Smith","firstname":"Mary","company":"Vtiger","email":"mary_smith#company.com","id":"10x32"}]}})
i am trying to retrieve the whole json result values using the following snippet
if (xmlHttp.readyState==4)
{
alert(xmlHttp.status);
if(xmlHttp.status==200)
{
alert("hi");
var jsondata=eval("("+xmlHttp.responseText+")") //retrieve result as an JavaScript object
jsonOutput=jsondata.result;
alert(jsonOutput);
InitializeLeadStorage()
}
}
my alert (hi ) is displayed but the alert(jsonOutput); is undefined , please help me if you could find any mistake
jsonOutput = jsondata.message.result;
result lives on message - it is not a top-level item in the JSON. With things like this, console.log() the JSON and you can check the path to the bit you want.
Also
your variable is global
there are better ways of parsing your JSON. If you don't care about old IEs, you can use the ECMA5 JSON.parse(), else use jQuery or another third-party utility for this