Flex3 issue to get the array format using json object - actionscript-3

{"object":[{"cyclename":"PE cycle","avgRunTime":"05:30","actualStartTime":"08/27/2011 02:40:08","actualEndTime":"08/27/2011 05:26:38","startTime":"02:40","status":"G"}]}
this is my file and i want to parse it to array and get the status displayed but i am getting data like [object object][object Object],[object Object],[object Object] etc...
how do i parse it to a dataprovider and code i have written is
private function cycle_resultHandler(event:ResultEvent):void
{
var myData:Object = JSON.decode(event.result as String);
for(var i:String in myData['object'])
{
dProvider.addItem(myData['object'][i]);
}
}

Your looping seems to be a bit off. First off you may want to reconsider your usage of a "for ...in" loop vs. a "for each" loop. This article: for...in vs. for each explains the differences quite plainly.
You may also want to give this article a read for more information on object introspection (a technique for determining the properties of a class at runtime -- what you are trying to do...).
In any case, the issue here is what you are looping over. If the goal here is to loop over the property values of "object" and add them to an array or arraycollection, you're almost there--
utilizing a "for each" loop you might do this instead:
private function cycle_resultHandler(event:ResultEvent):void {
var myData:Object = JSON.decode(event.result as String);
//Here we are iterating over the values in the "object" object as opposed to it's keys.
for each(var str:String in myData['object']) {
dProvider.addItem(str);
}
}
Hope this helps :)

Related

Why I Can't Write Objects in <li> Tag

When I writing my JSON data to HTML tag it's writing but don't write object. It's write [object Object]:
○Data1 ○wash dishes ○[object Object]
○find some break ○[object Object]
I'm trying to do lists with pointing JSON database but it's looks like that. I'm calling my JSON with that code:
var db_note = objpick(data);
db_note.date.forEach(function(element) {
tabledatednote.insertAdjacentHTML( 'beforeend',"<li>" + element + " </li>");
/* I just writed to this part because is just changing "no_date.>date<" part while displaying other JSONs */
});
objpick.js is an external file
function objpick(data){
for(i in data){ var result = data[i] }
return result
};
and there is my JSON database
{
"nodate": ["wash dishes", "find some bread"],
"date": [{"01/01/2077" : "Cyberpunk Meet"}, {"25/05/2005" : "Buney?"}],
"bookmark" : ["Data1"]
}
Ultimately what's being displayed is a string. So the code converts whatever you want to display to a string. For simple values, this conversion is easy. It's consistent and obvious what the resulting string is for a single value.
But objects are not simple values. They are potentially complex. And unless otherwise defined on your object(s), the default string representation for an object is: [object Object]
Some of the things you are display are values:
"find some bread"
But some of them are objects:
{"25/05/2005" : "Buney?"}
For the objects, you'd need to tell the code how to display it. Some options I can think of are:
Manually. For example, check if a certain property exists on the object and, if it does, display that property's value.
JSON-encode the object and display the resulting JSON string.
Override .toString() on your object(s).
Which you choose is up to you, and for the same reason that you're seeing the current default behavior... Because only you know how you want/expect that object to be displayed.

Angular 8 JSON.parse not parsing completely/impartially

I receive a JSON object that looks like this:
this data is being passed through a Socketio emit, so the angular HttpClient is not intercepting it.
{
"single":[
{
"name":"Xavi555",
"data":[
{
"_id":"5e2ea609f8c83e5435ebb6e5",
"id":"test1",
"author":"someone",
"recipient":"someone",
"content":"test",
"msgId":"Testid",
"gNamespace":""
}
]
}
],
"group":[]
}
however when I use JSON.parse() on the object above The key data does not contain the value of data that is to say:
private func(jsonObj: string): void {
console.log(jsonObj);
}
I see:
single: Array(1)
groups: Array(0)
single Array(1)
name: test
data: Array(0)
I thought it was an issue with deep cloning, but, when trying to do JSON.parse(JSON.stringify(jsonObj)) it returns the original json string object.
related but no solution posted
actual code:
private handleStoredMessages(dirtyObj: string): void {
// debugger;
const cleanObj = JSON.parse(dirtyObj);
const { single, group } = cleanObj;
console.log('raw json', dirtyObj);
onsole.log('clean json', cleanObj);
}
any ideas?
If you are using angular, then I doubt you should be using JSON.parse. This is handled by the HttpClient. Nevertheless, your assumption about your data structure is wrong. The single is an array of objects, not an object itself:
So to access the .data you need to do jsonObj.single[0].data. Which in itself is an array again
The only other reason this could happen, is because you modify the object/array somewhere else in your code, before you actually press the triangle in console to open the object. Hover on the blue information icon to see why.
Value below was evaluated just now
The object is lazily evaluated, meaning that if you did any transformations to the object, it will show that state, not the state at the moment you logged the object.
The issue of this was that the back end guy double encoded and did some weird stuff not my fault

JSON.parse and JSON.stringify are not idempotent and that is bad

This question is multipart-
(1a) JSON is fundamental to JavaScript, so why is there no JSON type? A JSON type would be a string that is formatted as JSON. It would be marked as parsed/stringified until the data was altered. As soon as the data was altered it would not be marked as JSON and would need to be re-parsed/re-stringified.
(1b) In some software systems, isn't it possible to (accidentally) attempt to send a plain JS object over the network instead of a serialized JS object? Why not make an attempt to avoid that?
(1c) Why can't we call JSON.parse on a straight up JavaScript object without stringifying it first?
var json = { //JS object in properJSON format
"baz":{
"1":1,
"2":true,
"3":{}
}
};
var json0 = JSON.parse(json); //will throw a parse error...bad...it should not throw an error if json var is actually proper JSON.
So we have no choice but to do this:
var json0= JSON.parse(JSON.stringify(json));
However, there are some inconsistencies, for example:
JSON.parse(true); //works
JSON.parse(null); //works
JSON.parse({}); //throws error
(2) If we keep calling JSON.parse on the same object, eventually it will throw an error. For example:
var json = { //same object as above
"baz":{
"1":1,
"2":true,
"3":{}
}
};
var json1 = JSON.parse(JSON.stringify(json));
var json2 = JSON.parse(json1); //throws an error...why
(3) Why does JSON.stringify infinitely add more and more slashes to the input? It is not only hard to read the result for debugging, but it actually puts you in dangerous state because one JSON.parse call won't give you back a plain JS object, you have to call JSON.parse several times to get back the plain JS object. This is bad and means it is quite dangerous to call JSON.stringify more than once on a given JS object.
var json = {
"baz":{
"1":1,
"2":true,
"3":{}
}
};
var json2 = JSON.stringify(json);
console.log(json2);
var json3 = JSON.stringify(json2);
console.log(json3);
var json4 = JSON.stringify(json3);
console.log(json4);
var json5 = JSON.stringify(json4);
console.log(json5);
(4) What is the name for a function that we should be able to call over and over without changing the result (IMO how JSON.parse and JSON.stringify should behave)? The best term for this seems to be "idempotent" as you can see in the comments.
(5) Considering JSON is a serialization format that can be used for networked objects, it seems totally insane that you can't call JSON.parse or JSON.stringify twice or even once in some cases without incurring some problems. Why is this the case?
If you are someone who is inventing the next serialization format for Java, JavaScript or whatever language, please consider this problem.
IMO there should be two states for a given object. A serialized state and a deserialized state. In software languages with stronger type systems, this isn't usually a problem. But with JSON in JavaScript, if call JSON.parse twice on the same object, we run into fatal exceptions. Likewise, if we call JSON.stringify twice on the same object, we can get into an unrecoverable state. Like I said there should be two states and two states only, plain JS object and serialized JS object.
1) JSON.parse expects a string, you are feeding it a Javascript object.
2) Similar issue to the first one. You feed a string to a function that needs an object.
3) Stringfy actually expects a string, but you are feeding it a String object. Therefore, it applies the same measures to escape the quotes and slashes as it would for the first string. So that the language can understand the quotes, other special characters inside the string.
4) You can write your own function for this.
5) Because you are trying to do a conversion that is illegal. This is related to the first and second question. As long as the correct object types are fed, you can call it as many times as you want. The only problem is the extra slashes but it is in fact the standard.
We'll start with this nightmare of your creation: string input and integer output.
IJSON.parse(IJSON.stringify("5")); //=> 5
The built-in JSON functions would not fail us this way: string input and string output.
JSON.parse(JSON.stringify("5")); //=> "5"
JSON must preserve your original data types
Think of JSON.stringify as a function that wraps your data up in a box, and JSON.parse as the function that takes it out of a box.
Consider the following:
var a = JSON.stringify;
var b = JSON.parse;
var data = "whatever";
b(a(data)) === data; // true
b(b(a(a(data)))) === data; // true
b(b(b(a(a(a(data)))))) === data; // true
That is, if we put the data in 3 boxes, we have to take it out of 3 boxes. Right?
If I put my data in 2 boxes and take it out of 1, I'm not holding my data yet, I'm holding a box that contains my data. Right?
b(a(a(data))) === data; // false
Seems sane to me...
JSON.parse unboxes your data. If it is not boxed, it cannot unbox it. JSON.parse expects a string input and you're giving it a JavaScript object literal
The first valid call to JSON.parse would return an object. Calling JSON.parse again on this object output would result in the same failure as #1
repeated calls to JSON.stringify will "box" our data multiple times. So of course you have to use repeated calls to JSON.parse then to get your data out of each "box"
Idempotence
No, this is perfectly sane. You can't triple-stamp a double-stamp.
You'd never make a mistake like this, would you?
var json = IJSON.stringify("hi");
IJSON.parse(json);
//=> "hi"
OK, that's idempotent, but what about
var json = IJSON.stringify("5");
IJSON.parse(json);
//=> 5
UH OH! We gave it a string each time, but the second example returns an integer. The input data type has been lost!
Would the JSON functions have failed us here?
var json = JSON.stringify("hi");
JSON.parse(json);
//=> "hi"
All good. And what about the "5" ?
var json = JSON.stringify("5");
JSON.parse(json));
//=> "5"
Yay, the types have been preseved! JSON works, IJSON does not.
Maybe a more real-life example:
OK, so you have a busy app with a lot of developers working on it. It makes
reckless assumptions about the types of your underlying data. Let's say it's a chat app that makes several transformations on messages as they move from point to point.
Along the way you'll have:
IJSON.stringify
data moves across a network
IJSON.parse
Another IJSON.parse because who cares? It's idempotent, right?
String.prototype.toUpperCase — because this is a formatting choice
Let's see the messages
bob: 'hi'
// 1) '"hi"', 2) <network>, 3) "hi", 4) "hi", 5) "HI"
Bob's message looks fine. Let's see Alice's.
alice: '5'
// 1) '5'
// 2) <network>
// 3) 5
// 4) 5
// 5) Uncaught TypeError: message.toUpperCase is not a function
Oh no! The server just crashed. You'll notice it's not even the repeated calling of IJSON.parse that failed here. It would've failed even if you called it once.
Seems like you were doomed from the start... Damned reckless devs and their careless data handling!
It would fail if Alice used any input that happened to also be valid JSON
alice: '{"lol":"pwnd"}'
// 1) '{"lol":"pwnd"}'
// 2) <network>
// 3) {lol:"pwnd"}
// 4) {lol:"pwnd"}
// 5) Uncaught TypeError: message.toUpperCase is not a function
OK, unfair example maybe, right? You're thinking, "I'm not that reckless, I
wouldn't call IJSON.stringify or IJSON.parse on user input like that!"
It doesn't matter. You've fundamentally broken JSON because the original
types can no longer be extracted.
If I box up a string using IJSON, and then unbox it, who knows what I will get back? Certainly not you, and certainly not the developer using your reckless function.
"Will I get a string type back?"
"Will I get an integer?"
"Maybe I'll get an object?"
"Maybe I will get cake. I hope it's cake"
It's impossible to tell!
You're in a whole new world of pain because you've been careless with your data types from the start. Your types are important so start handling them with care.
JSON.stringify expects an object type and JSON.parse expects a string type.
Now do you see the light?
I'll try to give you one reason why JSON.parse cannot be called multiple time on the same data without us having a problem.
you might not know it but a JSON document does not have to be an object.
this is a valid JSON document:
"some text"
lets store the representation of this document inside a javascript variable:
var JSONDocumentAsString = '"some text"';
and work on it:
var JSONdocument = JSON.parse(JSONDocumentAsString);
JSONdocument === 'some text';
this will cause an error because this string is not the representation of a JSON document
JSON.parse(JSONdocument);
// SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
in this case how could have JSON.parse guessed that JSONdocument (being a string) was a JSON document and that it should have returned it untouched ?

Manually parse json data according to kendo model

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.

Is there a way to "grep" for a keyword in a JavaScript object in Chrome Dev Tools?

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}