from json object to my object properties - javascript

This is a little hard to explain. I got this from server:
{"enable": "15,16,17,18,19,20,21,22,23",
"disable": "{ from: new Date(2014,9,16,23,0), to: new Date(2014,9,16,23,0) }"}
and this is how I try to set the enabled and disables hours to my pickatime object from that JSON object. (http://amsul.ca/pickadate.js/api.htm#method-set-disable-enable)
$.get('/ajax/res/', function(data) {
var picker = $("#rz-time-1").pickatime('picker');
picker.set('enable', [
data.enable
]);
picker.set('disable', [
data.disable
]);
}, 'json');
this doesn't work, however if I put $.parseJSON(data.enable) it works only if there is not commas in my string... otherwise I get unexpected non-whitespace character because of the commas...

The new Date(2014,9,16,23,0) in your JSON is invalid. Also, why is the disable value a string? It looks like it should not.
Instead of using new Date(...), you could possibly use an array:
{
"enable": "15,16,17,18,19,20,21,22,23",
"disable": {
"from": [2014,9,16,23,0],
"to": [2014,9,16,23,0]
}
}
Now you can access the specific parts of what was the illegal new Date.

Related

convert time string to date object javascript

I'm trying to plot D3 timeseries by referring :
http://mcaule.github.io/d3-timeseries/
which takes Date in this format : 'new Date('2013-01-01')
Now, I have following array:
var data =[{
"time": "2017-06-23T23:37:20-07:00",
"value": 25.189767114257663
},
{
"time": "2017-06-23T23:37:30-07:00",
"value": 24.637318860009692
},
{
"time": "2017-06-23T23:37:40-07:00",
"value": 24.896462306379043
},
{
"time": "2017-06-23T23:37:50-07:00",
"value": 24.348000192323468
}]
I need to give this array as input to the d3 timeseries function. But I'm unable to plot anything as above time is not a Date object. How do I append or convert that time string to date object. Because I absolutely need to have that new Date thing otherwise that function is not at all executing.
I tried to convert time into date object using:
data.map(function(ele) {
ele.time = new Date(ele.time);
});
So, this thing appended Zone to all the times. When I tried to give this array as input to d3 function, it doesn't work.
You can map the timestamp to a date object by iterating over data and assigning a new field called date.
data.forEach(function(elem, index, arr) {
arr[index]['date'] = new Date(
arr[index]['timestamp'].split('T')[0]);
});
Pretty basic string splitting, and there are probably more elegant solutions, but here's a start.

How to pretty print JSON inside sap.ui.layout.form.SimpleForm

I'm trying to pretty print a JSON variable inside sapui5 form. I have this below code:
var dataActualMeasure, oModelActualMeasure;
function initActualMeasure() {
dataActualMeasure = {
status: ""
}
oModelActualMeasure = new sap.ui.model.json.JSONModel();
oModelActualMeasure.setData(dataActualMeasure);
sap.ui.getCore().setModel(oModelActualMeasure, "actualMeasure");
};
initActualMeasure();
function updateMeasures() {
oModelActualMeasure.loadData(url + "/?action=Status");
oModelActualMeasure.attachRequestCompleted(
function() {
oModelActualMeasure.refresh();
});
}
var measuresForm = new sap.ui.layout.form.SimpleForm(
"measuresForm", {
maxContainerCols: 1,
editable: true,
content: [
new sap.ui.core.Title({
text: "Kafka Status"
}),
new sap.m.Label({
text: "Status"
}),
new sap.m.Input({
value: "{actualMeasure>/status}"
}).setEditable(false)
]
});
var page = new sap.m.Page("page", {
title: "Results",
content: [
measuresForm
]
});
The window is refreshed every 1 second, so a new jSON value will be assigned to the variable 'status' every second which is getting printed in the page but not pretty printed. How shall I pretty print it.
I tried declaring
var jsonString = JSON.stringify(oModelActualMeasure.getData().status);
and include this variable in the page content[], but this is not helping me. Please help me. I'm beginner in sapui5.
Use JSON.stringify parameters.
//JSON.stringify(value[,replacer[, space]])
var jsonString = JSON.stringify(oModelActualMeasure.getData().status, null, '\t');
space will do the following (from developer.mozilla.org):
A String or Number object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 if it's larger than that. Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.

Get comma separated string from array

I have the following JSON in JS.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":["num_domains", "med_load_time", "avg_load_time", "tot_req"]
}
I want the list of alerts to be removed and replaced with comma separated values as follows.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":"num_domains,med_load_time,avg_load_time,tot_req"
}
Just adding all the steps:-
1). Taking your JSON in a variable.
data = {"url":"http://example.com/main.aspx","report_template_id":"1","interval_secs":"86400","analysis_type":"lite","email":"rokumar#example.com","alerts":["num_domains","med_load_time","avg_load_time","tot_req"]};
2). Parse JSON data to object. Assuming the JSON is a string initially do a typeof(data) to be clear.
data = JSON.parse(data);
3) Change list of alerts to comma separated values
data.alerts = data.alerts.join(',');
4) Convert back to string
data = JSON.stringify(data)
So data will look like
{
"url": "http://example.com/main.aspx",
"report_template_id": "1",
"interval_secs": "86400",
"analysis_type": "lite",
"email": "rokumar#example.com",
"alerts": "num_domains,med_load_time,avg_load_time,tot_req"
}
Note:- If you will just say join() then also it will work, because default delimiter is , only, just to clarify I have given that.

How can i convert this AJAX json result (which has a key/value property) into a javascript array

Given the following json result, how can I convert the validationErrors key/value property into a nice array object in javascript so i can then do things like
errors[0].Key
or
errors[0].Value, etc...
NOTE: If it's easier to do the conversion with jQuery, then I'm happy to use that. Also, I'm getting the data via jQuery -> $.post...)
update:
Here's the actual json data so someone can answer this with JSFiddle please.
{
"aaaa": 0,
"bbbb": 0,
"cccc": null,
"validationErrors": {
"a1_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "Invalid PropertyType. Please choose any property except Unknown.",
"a2_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "A State is required. Eg. Victoria or New South Wales.",
"b1_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "Invalid PropertyType. Please choose any property except Unknown.",
"b2_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "A State is required. Eg. Victoria or New South Wales.",
"c1_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "Invalid PropertyType. Please choose any property except Unknown.",
"c2_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "A State is required. Eg. Victoria or New South Wales."
}
}
I would take all the keys of the object and then map them to an array.
var arrayOfErrors = Object.keys(objectOfErrors).map(function(errorKey) {
return objectOfErrors[errorKey];
});
You can use map to convert the object to an array:
var errors = jQuery.map(data.validationErrors, function (value, key) {
return {
"Key": key,
"Value": value
};
});
JSFiddle showing this approach: http://jsfiddle.net/WgaFb/1/
If you do not wish to use jQuery, here is a pure JavaScript method:
var errors = [];
for(var key in data.validationErrors) {
errors.push({
"Key": key,
"Value": data.validationErrors[key]
});
}
JSFiddle for this second approach: http://jsfiddle.net/4WXEF/1/

Javascript and Parsed JSON - Child node's ['#attributes'].type returns undefined

I've parsed a legitimate JSON object and I'm walking through the multidimensional array to first find the year based on a function argument and then the month within that year.
My for loops are nested:
for (year in yearsData) {
//If we've found the correct year...
if (yearsData[year]['#attributes'].name == yearToGet) {
//...walk through that year's child months
for (month in yearsData[year]) {
//This works!
console.log(yearsData[year][month]);
//This also works!
console.log(yearsData[year][month]['#attributes']);
//This does not work! ..but this is what I need!
console.log(yearsData[year][month]['#attributes'].name);
}
}
I can track the object in Firebug's console (with valid output) all the way up to
console.log(yearsData[year][month]['#attributes']);
But the instant I add the type at the end (.name):
yearsData[year][month]['#attributes'] is undefined.
console.log(yearsData[year][month]); returns the valid object, and I can see the valid #attributes listed.
I've checked the spelling multiple times; I've changed the name of the attribute to other things in case it was somehow conflicting with year's attributes..but I got nothin'.
What simple thing am I missing?
The JSON:
{
"year": [
{
"#attributes": {
"name": "2013"
},
"month": {
"#attributes": {
"name": "January"
},
"winner": "None!",
"theme": "Nobody!"
}
}
]
}
Think about using jQuery.grep or jQuery.each to work efficiently on object iteration and analysis. It can help a lot.
http://api.jquery.com/jQuery.grep/
After some more brainbashing, it turned out to be a super derp. I was using month the variable rather than the string 'month' that would ID it.
I'd need to use: console.log(yearsData[year]['month']['#attributes'].name);
To get it. Whoo.

Categories

Resources