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.
Related
I am parsing a JSON object containing several key value pairs but am not sure how to make objects out of the JSON below. The keys are always different depending on the GET request so I am not able to use json['keyname'] like usual. What kind of function would I need in order to return a list of keys from 'ccwms' and a respective list of values (floats)?
{
"ccwms": {
"frc118": 160.8076758518209,
"frc1255": 15.257951313413884,
"frc1296": 11.42077882954301,
"frc7321": -161.58464745359254
}
}
After parsing the JSON, you have a normal Dart Map with string keys and some values. You can iterate maps in several ways, for example:
for (var key in map.keys) { doSomething(key, map[key]); }
for (var entry in map.entries) { doSomething(entry.key, entry.value); }
map.forEach(doSomething);
(Map.keys, Map.entries, Map.forEach).
I'm sure there are more ways to access all the keys and values.
What you do with the keys and values is up to you, it's just a map.
Minimal Dart program to convert a json string:
import 'dart:convert';
main() {
String source = """{"X":"RRRR","Y":"SSSS","ccwms": {
"frc118": 160.8076758518209,
"frc1255": 15.257951313413884,
"frc1296": 11.42077882954301,
"frc7321": -161.58464745359254
}}""";
dynamic target = JsonDecoder().convert(source);
print ( source.toString());
}
Are these keys random ? I think keys have to be predefined set, because json is a serialization for already existed object and the object structure can not be random
hope I understand correctly
should be a comment but I can not add comments right now.
I've noticed that the Set in ES2015 does not implement a simple toJSON function, such as serializing to an array. Below is the implementation I came up with that does just that:
Object.defineProperty(Set.prototype, 'toJSON', {
enumerable: false,
value: function () {
return [...this];
}
});
Is there any reason why a Set does not serialize to an array?
Are there any edge cases where this override for toJSON is a bad idea?
See this answer as to why there can't be a general toJSON case for Maps, and for similar reasons, Sets. Basically, keys and/or Set items can be anything, including objects and references to other things that can't be serialized into JSON (which, remember, is a specific format with specific, stricter rules than just "turn into intelligible data of another type"). What you want here is more like "toArray" anyhow. You method already works for that inline, as would Array.from(Set), I think.
But if you wanted to add this sort of method to the prototype for your own internal usage without risking possible problems if a similar (but not identical) method is ever added, you could use a Symbol key'd prop.
var toArray = Symbol('toArray');
Object.defineProperty(Set.prototype, toArray, {
enumerable: false,
value: function () {
return [...this];
}
});
var g = new Set();
g.add(9);
g[toArray]();//-> [9]
If you do that, then you are guaranteed to not cause problems with anything other than your own code, since only your code will have access to the toArray Symbol key that references that method.
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.
I've looked at this question (Is there a native feature to convert string based JSON into Mongoose Schema object instance?) and it's related to my question but doesn't do exactly what I'm looking for.
Essentially, I have JSON I've fetched from an Express response and I'd like to cast it to a Mongoose object for the purposes of calling a schema method on the object.
My schema looks something like this:
var BlahSchema = new Schema({
folder: String,
filename: String,
original: String
});
...
// This is the function I wish to cal
BlahSchema.virtual('url').get(function () {
...
});
From what I understand, when I have an object matching BlahSchema, I can call the method via a simple object.url.
I have two questions. First, the JSON I'm retrieving these objects from erases their schema, right? I'm retrieving these from the database via Blah.search(...function(err, blahs)). This all gets encoded into a JSON object which I return via callback(req, res, search_result) where search_result is an object created via search_result.blahs = blahs, etc. Is there any way to preserve this schema across calls? This would be the preferred method.
Second, if the above is not possible, how do I re-cast JSON to schema without using the save() function mentioned in the answer to the question I pose above? I don't want to re-add objects to the database; I just want to use a method defined for that schema.
EDIT: Express is pretty sick. All you have to do is blah(object).method_name, where blah = mongoose.model('blah')
I save a User (Schema) object to redis in plain JSON.
Get the userData (string) and parse it to JSON object:
var user = new User(JSON.parse(userData))
... and you have all the methods of your User schema.
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