Converting date and time from response JSON in human readable format - json

The date and time in a response JSON looks like this:
2019-02-17T05:28:00
I tried to convert it with Regex to the following format:
17.02.2019 at 05:28:00
But failed.
let string = string
.split("T")
.join("")
.split("-")
.join("");
string = string.replace(
/(\d{4})(\d{2})(\d{2})(\d{8})/,
"$3$2$1$4"
);
What is the right way?

You can capture year month date and time in different groups using this regex,
(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})
And replace it with this,
$3.$2.$1 at $4
Demo
Javascript demo,
var s = "2019-02-17T05:28:00"
console.log(s.replace(/(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})/g,'$3.$2.$1 at $4'))

Your best bet is probably to use a date-time handling library such as Moment.js, which provides all sorts of nice date manipulation functionality.
You can then do things like
const moment = require("moment");
let formattedDate = moment.utc(isoDateVariable, moment.ISO_8601).format("DD/MM/YYYY");
It also helps you with all the general nastiness associated with dates and times in programs which you really don't want to be handling yourself.

Related

Extract group of characters from an object/string

I have a very long string of characters that contain a date and time. How can I extract just the date part and the time part from it?
Here's the string:
0:2019010309130000:0.000000:126:0
I just need to extract the date and the time as in:
Date - 20190103
Time - 0913 and format it as 09:13
This applies to Python programming language.:
If the string stays in the same format I believe you should be able to extract it using a concept known as "slicing" (you can find more about it in here).
x = "0:2019010309130000:0.000000:126:0"
y = 'Date - {} Time - {}:{}'.format(x[2:10], x[10:12], x[12:14])
print(y)

convert excel to json file

I'm new in creating jsons and having bais knowledge of java.
I'm trying to convert database table data to json.
Having option to store table data in any format of file than convert that into json.
Here is my table data.
Table: PKGS
Price, pd, Id, Level
1 , 266 , 59098 , 5
2 , 247 , 59098 , 5
I want my table data in this json format. Its just an example...to show level in JSON
"Id":59098
"pd":266
"Level":5
"price":1
"Id":59098
"pd":247
"Level":5
"price":2
In this json there is two loops are going If am not wrong. I was able to do it for one loop in ETL..but couldnt do it for two loops.
Not getting values for reimbursementId and packageId
Have goggled alot but couldn't find any code to understand properly and approach for the same.
Code tried little bit
FileInputStream inp = new FileInputStream("D:/json.xlsx" );
Workbook workbook = WorkbookFactory.create( inp );
Sheet sheet = workbook.getSheetAt( 0 );
JSONObject json = new JSONObject();
JSONArray rows = new JSONArray();
but dont know what to next !!
can anyone tell me how to do this ?
I advice you to use a specific tool. This is not a whole new case.
Try Talend Open Studio. It is not so complicate to use if you want to convert a file (CSV, JSON, Database directly, etc) to another. Please see TalendForge for basics.
In your case, you can connect to your database, and send all data in JSON.
Edit:
Your representation is not following the same logic than JSON. Here how I see it (and this is probably wrong because I can't understand)
If you just want Excel to JSON without any changes:
{
"rows":[
{
"Price":"1",
"pd":"266",
"Id":"59098",
"Level":"5"
},
{
"Price":"1",
"pd":"266",
"Id":"59098",
"Level":"5"
},
//and again and again
{
"Price":"2",
"pd":"247",
"Id":"59098",
"Level":"5"
}
]
}
If you want to reorganize, then define what you want. Try to imagine a sample of your data in a Java Object using ArrayList, int, String and subclass or even better in a JavaScript Object.
For the last example it will give you:
public class myJson{
ArrayList<myObject> rows;
with
public class myObject{
String Price;
String pd;
String Id;
String Level; //Or int, or date, or whatever
If you want to reorganize your data model, please give us this model.
Converting Excel file data to Json format is a a bit complex process, it depends on the structure of data, we do not have exact online tool as such so far...
custom code is required, there are various technologies available to be used, but best suited should be VBA, because VBA fits within Excel and can generate Json file quickly and flexible to edit code compared to any other technology that requires to automate to excel and import data and then process.
We can find there are various websites provide code to generate json from excel data, here is one such site looks expertise in this area. http://www.xlvba.net/tools/excel-automation-to-convert-excel-data-to-json-format.html
Ragavendra

google app scripts Utilities.FormatDate malfunction

In need to obtain a date in a integer format ddmmyyyy using as argument a cell that contains a date in standard google spreadsheet format.
That's the code.
function getDateToInt(date) {
ddmmyyyy = Utilities.formatDate(date,SpreadsheetApp.getActive().getSpreadsheetLocale(),'dd/MM/yyyy');
var array = new Array();
array = (ddmmyyyy.split('/'));
return (parseInt(array[2])*100+parseInt(array[1]))*100+parseInt(array[0]);
}
Here the problem:
The function behave as expected in all case except when the month in the argument date is 8 or 9. In these cases returns #NUM!.
Any contribution is welcome.
If you are interested in using just a formula, the formula
=value(A1)
where a1 is a standard date such as 1/1/2016 with return "42370"
the number integer of the date.
parseInt() uses 2 arguments, the variable to parse and the base.
The base is frequently omitted and assumed to be 10 but this is actually not ideal. Read the doc here.
I guess that adding the base parameter will solve the issue you have but you can alternatively use the Number() function which will also convert the string into a number.

Use a period in a field name in a Matlab struct

I'm using webwrite to post to an api. One of the field names in the json object I'm trying to setup for posting is odata.metadata. I'm making a struct that looks like this for the json object:
json = struct('odata.metadata', metadata, 'odata.type', type, 'Name', name,);
But I get an error
Error using struct
Invalid field name "odata.metadata"
Here's the json object I'm trying to use in Matlab. All strings for simplicity:
{
"odata.metadata": "https://website.com#Element",
"odata.type": "Blah.Blah.This.That",
"Name": "My Object"
}
Is there a way to submit this json object or is it a lost cause?
Field names are not allowed to have dots in them. The reason why is because this will be confused with accessing another nested structure within the structure itself.
For example, doing json.odata.metadata would be interpreted as json being a struct with a member whose field name is odata where odata has another member whose field name is metadata. This would not be interpreted as a member with the combined field name as odata.metadata. You're going to have to rename the field to something else or change the convention of your field name slightly.
Usually, the convention is to replace dots with underscores. An automated way to take care of this if you're not willing to manually rename the field names yourself is to use a function called matlab.lang.makeValidName that takes in a string and converts it into a valid field name. This function was introduced in R2014a. For older versions, it's called genvarname.
For example:
>> matlab.lang.makeValidName('odata.metadata')
ans =
odata_metadata
As such, either replace all dots with _ to ensure no ambiguities or use matlab.lang.makeValidName or genvarname to take care of this for you.
I would suggest using a a containers.Map instead of a struct to store your data, and then creating your JSON string by iterating over the Map filednames and appending them along with the data to your JSON.
Here's a quick demonstration of what I mean:
%// Prepare the Map and the Data:
metadata = 'https://website.com#Element';
type = 'Blah.Blah.This.That';
name = 'My Object';
example_map = containers.Map({'odata.metadata','odata.type','Name'},...
{metadata,type,name});
%// Convert to JSON:
JSONstr = '{'; %// Initialization
map_keys = keys(example_map);
map_vals = values(example_map);
for ind1 = 1:example_map.Count
JSONstr = [JSONstr '"' map_keys{ind1} '":"' map_vals{ind1} '",'];
end
JSONstr =[JSONstr(1:end-1) '}']; %// Finalization (get rid of the last ',' and close)
Which results in a valid JSON string.
Obviously if your values aren't strings you'll need to convert them using num2str etc.
Another alternative you might want to consider is the JSONlab FEX submission. I saw that its savejson.m is able to accept cell arrays - which can hold any string you like.
Other alternatives may include any of the numerous Java or python JSON libraries which you can call from MATLAB.
I probably shouldn't add this as an answer - but you can have '.' in a struct fieldname...
Before I go further - I do not advocate this and it will almost certainly cause bugs and a lot of trouble down the road... #rayryeng method is a better approach
If your struct is created by a mex function which creates a field that contains a "." -> then you will get what your after.
To create your own test see the Mathworks example and modify accordingly.
(I wont put the full code here to discourage the practice).
If you update the char example and compile to test_mex you get:
>> obj = test_mex
obj =
Doublestuff: [1x100 double]
odata.metadata: 'This is my char'
Note: You can only access your custom field in Matlab using dynamic fieldnames:
obj.('odata.metadata')
You need to use a mex capability to update it...

Appropriate JSON date format when sending from JSP to jQuery

As JSON format doesn't standardize dates subformat, this task is completely on a programmer, right?
When sending dates from PHP to Javascript and back I sent dates as a single integer in UNIX timestamp format (number of seconds since 01/01/1970).
On server:
$now = new DateTime('now');
$now->getTimestamp();
On client:
.success : function (data)
{
var date = new Date(data * 1000);
}
What's the best format for sending dates from JSP? (I'm JSP and Java newbie).
Obviously, it has to be easy encoding/decoding using Java native classes as well as Javascript Date object.
There should not be any problems with overflowing (I'm afraid after 2038 my PHP code will break).
Regards,
new Date(milliseconds) //milliseconds since 1970/01/01 - so you've solved your own problem. I personally prefer to use yyyy-mm-dd hh:ii:ss format as it readable and different from UK and US formats.