1
I need to create a function that works over all parameters of a JSON object to search for data fields and manipulate them. Basically the object I can receive is something like:
{
idPedido:1,
dataCriado: "/Date(1454637600000-0200)/",
cliente: "Nome do Cliente",
pagamento:[
{
idPgto:1,
valor: 100.00,
tipoPgto:"dinheiro",
dataVenc:"/Date(1454637600000-0200)/"
},
{
idPgto:2,
valor: 100.00,
tipoPgto:"cartão",
dataVenc:"/Date(1454657600000-0200)/"
}
],
produtos:[
{
idProduto:1,
descricao:"bola",
valor:200.00
}
]
}
My problem is that there may be numerous variants that contain this date format (unfortunately the webservice I’m being forced to work with only sends me this way...)
I need to know how I can do a function that I can apply to all parameters that exist within JSON, regardless of the level of it. Today the function I’m using is this:
function corrigeData(d) {
if(d.indexOf('Date('){
d = d.replace(/\/Date\(/g, '').replace(/\)\//g, '');
d = new Date(d);
};
return d;
}
The problem is that I have to pick up and know where I’ll probably find the date field. But if you happen to change anything in my backend scope, I’ll have to go back and implement that too, which is unnecessary with a recursive function.
Any suggestions?
Not knowing which format versions you will receive is difficult to predict. Doubts: - why not use the parameter
-xxxx
of that date? - do you know if at least this webservice will always send timestamps? in that case you could use only.match(/\d{13}/)
and serves for all cases where there is a timestamp if the dates are modern.– Sergio
Yes, the webservice I know will send this format of data timestamps but in different fields.. instead of me doing a field-by-field treatment, I would prefer that where he hit a
param.indexOf('Date(')
it run the function in that parameter, updating the same.– LeandroLuk
in addition, the function corrigeData() above already makes the replacement I want, just need to know how to run it in all parameters independent of the level within the JSON
– LeandroLuk
Use the 13 digits that are timestamp giving a new date on it you already know has the date. And try to map the formats, and invalidate if something very unusual comes along. Webservice should support the dates concisely.
– flpms
Leandro, is it something like that? -> https://jsfiddle.net/j3Lquh7j/
– Sergio