defining date in json file - javascript

I wonder to know how to set today's date in json file like we are using in js.
Is there any option to specify Date.today() in json file?
Because, json data has date object which specifies system date whenever we read the json file.
Hope, you will understand what i am trying to say.
Thanks in advance,
-Raja.

Server side can generate JSON dates in ISO format for example "2012-04-30T02:15:12.356Z"
Then client side can parse and load into date object
new Date(Date.parse("2012-04-30T02:15:12.356Z"))

JSON is a structured transport format. It does not have logic in it.
But here are options:
Why not just get the date when you read the file instead?
Have a server generate that JSON that includes the date at which it was generated. However, this is not ideal if you want the current date. By the time you read the file, the date generated by the server is already past.
build a parser that parses a string and make it search for custom markup.
For example, special markup is contained in #{}. Get the command inside, determine the command, and execute replacement.
var jsonString = '{"data1" : "foo","date" : "#{currentdate}"}'
In this case, I'll find #{currentdate}. I should create a function corresponding to this command to replace #{currentdate} into the current date during read (in the format you want)
var parsedString = jsonString.replace(/#\{(\w+)\}/g, function(match, group) {
if (group === 'currentdate') {
return new Date();
}
else if (group === 'anotherCommand') {
return 'anotherValue';
} //and so on
});
and the result is like this:
jsonString = '{"data1" : "foo","date" : "Fri May 04 2012 01:17:07 GMT-0700 (PDT)"}'

I suggest that you consider using the JSON-js (json2.js) parser, because it parses all standard JSON, but also allows you to add custom parse handling logic, called a reviver function, which fits your scenario very well. The basic syntax to invoke the JSON parser with a custom handler looks like this:
var myObject = JSON.parse(myJSONtext, reviverFunction);
Using your example input as a guide, it could be set up to work like this:
var jsonTxt = '[{' +
'"data1": "foo",' +
'"Date": "",' +
'"childs": [{' +
'"data2": "stack",' +
'"Date": ""' +
'}{}{}...]}]'; //and-on-and-on as in your comment
myData = JSON.parse(jsonTxt, function ( key, value ) {
if ( key === 'Date') { return new Date(); }
//any additonal custom logic you may need later...
});
A general introduction to JSON-js is provided at the JSON in JavaScript page, along with some brief intro info about JSON, and the page also includes some usage scenarios.

You can consider leveraging popular library like moment.js http://momentjs.com/
Then you can store date as YYYY-MM-DD in json and let moment handle the parsing:
var dateString = '2012-11-01';
var someday = moment(dateString);
var formattedDate = someday.format('ddd, DD MMM YYYY'); // 'Thu, 01 Nov 2012'

If you want to store the date, I would prefer to store as a String with a format like yyyy/mm/dd hh:mm:ss or something like that, and parse it in a Date object when I want to read it in the language I need.
obj = {
dates : ['2012/04/30 10:14:23', '2012/05/01 05:34:01']
}
I don't understand exactly what you want, with eval methods (it's an ugly practice), you can add a method to puts the actual date in object, and also adds himself at the children and call the method added in the children.
obj = {
data : "foo",
addDate : function() {
this.date = newDate();
if (this.children) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].addDate = this.addDate;
this.children[i].addDate();
}
}
},
children : [{
data : "foo2"
}]
}
PS if you want to store it in a file, then you have to use the eval method (not recommended) storing the methods as a string or evry time you load the file do
jsonLoaded; // this var has the json that you store in a file;
var addDate = function() {
this.date = newDate();
if (this.children) {
for (var i = 0; i < this.children.length; i++) {
this.children[i].addDate = this.addDate;
this.children[i].addDate();
}
}
this.addDate = null; // remove the function we have added
// delete this.addDate; // if is compatible with browser
}
jsonLoaded.addDate = addDate;
jsonLoaded.addDate();
you cannot stringify json objects with functions, because of this, in the second method after add the method addDate, we remove that from the json object (also you can do delete this.addDate, but i don't know if it works in IE)

Wouldn't it be easier just to calculate the current system data whenever you read the file? I may be lacking context here but I don't see the point in storing that in the document.
If you really need to do so you can do as follows
var jsonObject = {"now":"new Date()"};
var date = eval(jsonObject.now);

it will be good to collect all the dates you want to transfer into a
Collection<String> dates = new ArrayList<String>();
Convert this collection to a json object and then at the receving end,convert it back to date. You can use joda date time API for conversions.

I use Gson in java to create json output, but Gson does not allow me to put javascript functions into the json. So this is what I do: Use replacement tags for the places you want to put code(like one of the earlier answers). Then get the text of the json, replace the tags, and then save the text to your json file:
Map<String, String> dynamicDates = new HashMap<>();
dynamicDates.put("d1", "new Date()");
dynamicDates.put("d2", "new Date(2015, 0, 1, 9, 30)");
dynamicDates.put("d3", "new Date(2015, 0, 1, 12, 30)");
JsonObject json = new JsonObject();
JsonObject root = new JsonObject();
JsonObject level_1_A = new JsonObject();
JsonObject level_1_B = new JsonObject();
json.add("root", root);
root.add("level_1_A", level_1_A);
root.add("level_1_B", level_1_B);
level_1_A.addProperty("d1", "${d1}");
level_1_A.addProperty("d2", "${d2}");
level_1_B.addProperty("d3", "${d3}");
StringBuilder sb = new StringBuilder();
new GsonBuilder().setPrettyPrinting().create().toJson(json, sb);
String str = sb.toString();
for (String key : dynamicDates.keySet()) {
str = str.replace("\"${" + key + "}\"", dynamicDates.get(key));
}
String jsonText = str;
String javascriptText = "var myJson = " + str + ";";
System.out.println(jsonText);
System.out.println(javascriptText);
So there is nothing left to be done on the consumption side in using this json. And the first output is:
{
"root": {
"level_1_A": {
"d1": new Date(),
"d2": new Date(2015, 0, 1, 9, 30)
},
"level_1_B": {
"d3": new Date(2015, 0, 1, 12, 30)
}
}
}
My use of json is usually saving it as javascript with an assignment, so this has been working for me.

Related

Club different MQTT Topic data into one JSON string in node red

How can I club all the MQTT Topic data in one JSON String
I was able to get JSON string for the individual topic only like this
"{"time":1549737900821,"payload":"1997.32","topic":"RotateZ"}"
{"time":1549737900821,"payload":"1954.32","topic":"RotateY"}"
but I want to display all the topic data in one JSON string only for example
"{"time":1549737900821,
"RotateZ":"1997.32",
"RotateY":"1954.32"}"
I am using mentioned below code in function node
var topic = msg.topic;
var d = new Date();
var t = d.getTime();
payload = {"time":t, "payload" : msg.payload ,"topic": topic }
msg.payload = payload;
return msg;
what modification will help me to make it work?
Any suggestion on this will be a great help
Try Join node. Set Manual, Combine each msg.payload to create a key/value object using the value of msg.topic as the key. On output add timestamp in simle function like this :
var d = new Date();
msg.payload.time = d.getTime();
return msg;

Are there some v8 functions to create a C++ v8::Date object from a string like "2015-02-20" without JS execution from C++?

JavaScript's date constructor can parse strings to create a date:
var date = new Date("2015");
console.log(date); // Thu Jan 01 2015 06:00:00 GMT+0600 (NOVT)
console.log(date.getTime()); // 1420070400000
I need a similar parsing (string to date) in my C++ Node.js addon.
I found two ways to get v8:Date:
static Local<Value> Date::New(Isolate* isolate, double time). It takes a double value.
static Date* Date::Cast(v8::Value* obj) But it simple converts string to double:
v8::Local<v8::String> str = Nan::New("2015").ToLocalChecked();
v8::Date *castDate = v8::Date::Cast(*str);
double castVal = castDate->NumberValue();
printf("%f\n", castVal); // 2015.000000, not 1420070400000 :(
v8::Local<v8::Date> newDate =
v8::Date::New(info.GetIsolate(), 2015).As<v8::Date>();
double newVal = newDate->NumberValue();
printf("%f\n", newVal); // 2015.000000
What methods are there in v8 for creating C++ v8::Date from a string?
UPDATE (2016.01.05):
I added "without JS execution from C++" to the question title.
I thought a bit out of the box and came up with some trickery:
v8::Local<v8::Date> tmp = Nan::New<v8::Date>(0).ToLocalChecked();
v8::Local<v8::Function> cons = v8::Local<v8::Function>::Cast(
Nan::Get(tmp, Nan::New("constructor").ToLocalChecked()).ToLocalChecked()
);
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {Nan::New("2015").ToLocalChecked()};
v8::Local<v8::Date> date = v8::Local<v8::Date>::Cast(
Nan::NewInstance(cons, argc, argv).ToLocalChecked()
);
First, I create an arbitrary Date object, then I extract the constructor function which is then used to effectively call new Date("2015").
You could also persist the constructor in your class for slightly more efficiency on frequent use.
How about using an one-off v8::Script for parsing your string?
(disclaimer: code not tested)
v8::Handle<v8::String> source = v8::String::New("new Date('2016-01-04')");
v8::Handle<v8::Script> script = v8::Script::Compile(source);
v8::Handle<v8::Value> result = script->Run();

Is there Any Way to Convert Mongo ObjectId into string by javascript/jquery

Is it possible to convert mongo objectId into string.
The above pictures shows data i received and shown in console.I need id value in string form .but ObjectId is returning as object
In Database id is look like this- 565d3bf4cefddf1748d1fc5e -objectId and i need id exactly like this –
According to the Mongo documentation:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
You can check it out here: https://docs.mongodb.org/manual/reference/object-id/
So in javascript you could do something like this.
var mId = {
Timestamp:1448950573,
Machine:13565407,
Pid:1756,
Increment:8888962
};
function getId(mongoId) {
var result =
pad0(mongoId.Timestamp.toString(16), 8) +
pad0(mongoId.Machine.toString(16), 6) +
pad0(mongoId.Pid.toString(16), 4) +
pad0(mongoId.Increment.toString(16), 6);
return result;
}
function pad0(str, len) {
var zeros = "00000000000000000000000000";
if (str.length < len) {
return zeros.substr(0, len-str.length) + str;
}
return str;
}
console.log(getId(mId))
It produces "565d3b2dcefddf06dc87a282" which was not exactly the id you had, but that might just be a tweak or i was working with different data :D.
EDIT
Added a padding function so that zeros are not truncated.
Hope that helps
EDIT:
I assume you are using c# to connect to and serve documents from the mongo DB. In that case, there is a driver that also supports toString().
Here is an example using the mongo csharp driver:
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
// ...
string outputFileName; // initialize to the output file
IMongoCollection<BsonDocument> collection; // initialize to the collection to read from
using (var streamWriter = new StreamWriter(outputFileName))
{
await collection.Find(new BsonDocument())
.ForEachAsync(async (document) =>
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
var line = stringWriter.ToString();
await streamWriter.WriteLineAsync(line);
}
});
}
ORIGINAL:
These are Mongo ObjectId's and if you haven't already deserialised the document they should support a toString method that will return a hexadecimal string.
but if you want this applied to the whole document, using JSON.stringify(MogoDocument) should deserialize this for you into a plain object.

How to convert a JSON lib formatted JSON date to a Javascript Date

Sourceforges JSON-lib (http://json-lib.sourceforge.net) produces a JSON date format like this:
{
"date":10,
"day":5,
"hours":0,
"minutes":0,
"month":5,
"nanos":0,
"seconds":0,
"time":1307660400000,
"timezoneOffset":-60,
"year":111 //this is 2011
}
Is there an easy way to convert this into a Javascript date object or should I just go through and set all the variables on the date object manually?
I've searched all over to find this with no luck! (apologies if the answer is lying around somewhere, I just can't seem to find it)
It looks like time is the epoch in msec, so you can just do: new Date(object['time'])
You will need to of course parse this into an object first.
It seems that in the json-lib project home page , there are no example explain the the process of Date.But as soon as you search json-lib's API,you will finally get the answer.
Here you can use this method below to process java.util.Date class. You can define your own format pattern and use the JsonConfig to register a custom JsonValueProcessor that used to process the Date class.
public static final JSON serializerObjWithFormatDate(Object javaObj){
String pattern = "yyyy-MM-dd HH:mm:ss";
final SimpleDateFormat fm = new SimpleDateFormat(pattern);
JsonConfig jsonCfg = new JsonConfig();
jsonCfg.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
#Override
public Object processObjectValue(String key, Object value, JsonConfig cfg) {
if (value == null) {
return "";
} else {
return fm.format((Date)value);
}
}
#Override
public Object processArrayValue(Object date, JsonConfig arg1) {
return fm.format((Date)date);
}
});
return JSONSerializer.toJSON(javaObj ,jsonCfg);
}
The param javaObj is the java object who has Date class instances.
May it be helpful .

"eval is evil", but do I have an option?

I've came up with some custom localization solution for a project I'm working on. The idea is that my HTML can contain this:
<h2 data-l10n="HELLO" data-l10n-params="['Visitor', new Date()]"></h2>
When the page is initiated a javascript function like this runs:
localizeAll: function(sel) {
var selector = sel || document,
$o = $(selector);
$o.find('[data-l10n]').each(
function() {
var $t = $(this),
val = $t.attr('data-l10n'),
params = $t.attr('data-l10n-params'),
po = null;
if (typeof params !== 'undefined') {
po = eval(params);
log(params, po);
}
var res = doLocalize(val, po);
if (res[0] !== '<') {
$t.text(res);
} else {
$t.text(val);
}
});
}
So basically we search for any elements that have a data-l10n-attribute and call doLocalize() for each of those objects. Additionally, the element can have a data-l10n-params-attribute, which is just a string literal that can be parsed to an array. This string is evaluated (params string becomes po array) and po is supplied to doLocalize() as the optional second parameter.
Hence, the output in Firebug (from log(params, po); statement) is:
['Vistor', new Date()] ["Vistor", Date {Thu Nov 17 2011 10:10:31 GMT+0100 (CET)}]
So yes, I'm using eval. And yes, I know that "eval is evil". But occasionally, I need to pass a parameter to doLocalize().
How could this be done without eval?
I think your problem is that you are effectively embedding JavaScript in HTML (which is against the unobtrusive JavaScript principle).
In your place I would add an extra l18n-params.js file with the following contents:
var dataL10Nparams = {
HELLO = ['Visitor', new Date()]
}
Now instead of reading the params from HTML attribute and evaluating just call:
dataL10Nparams['HELLO']
If you only provide parameterized values in your HTML attribute, consider using JSON.parse() instead of evaluation.

Categories