Javascript 在json文件中定义日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10311012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:48:18  来源:igfitidea点击:

defining date in json file

javascriptjsondate

提问by Rajagopal ?

I wonder to know how to set today's date in json file like we are using in js.

我想知道如何在 json 文件中设置今天的日期,就像我们在 js 中使用的那样。

Is there any option to specify Date.today() in json file?

是否有任何选项可以在 json 文件中指定 Date.today()?

Because, json data has date object which specifies system date whenever we read the json file.

因为,每当我们读取 json 文件时,json 数据都有指定系统日期的日期对象。

Hope, you will understand what i am trying to say.

希望,你会明白我想说什么。

Thanks in advance,

提前致谢,

-Raja.

-拉贾。

采纳答案by Joseph

JSON is a structured transport format. It does not have logic in it.

JSON 是一种结构化的传输格式。它没有逻辑。

But here are options:

但这里有选项:

  1. Why not just get the date when you read the file instead?

  2. 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.

  3. build a parser that parses a string and make it search for custom markup.

  1. 为什么不直接获取读取文件的日期呢?

  2. 让服务器生成包含生成日期的 JSON。但是,如果您想要当前日期,这并不理想。当您读取文件时,服务器生成的日期已经过去。

  3. 构建一个解析字符串并使其搜索自定义标记的解析器。

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)

在这种情况下,我会找到@{currentdate}. 我应该创建一个与此命令相对应的函数以@{currentdate}在读取期间替换为当前日期(以您想要的格式)

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)"}'

回答by

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

服务器端可以生成 ISO 格式的 JSON 日期,例如“2012-04-30T02:15:12.356Z” 然后客户端可以解析并加载到日期对象中

new Date(Date.parse("2012-04-30T02:15:12.356Z"))

回答by Sean Mickey

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 reviverfunction, which fits your scenario very well. The basic syntax to invoke the JSON parser with a custom handler looks like this:

我建议您考虑使用JSON-js( json2.js) 解析器,因为它解析所有标准 JSON,但也允许您添加自定义解析处理逻辑,称为reviver函数,非常适合您的场景。使用自定义处理程序调用 JSON 解析器的基本语法如下所示:

var myObject = JSON.parse(myJSONtext, reviverFunction);

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.

JSON in JavaScript page 中提供了对 JSON-js 的一般介绍,以及一些关于 JSON 的简要介绍信息,该页面还包括一​​些使用场景。

回答by 250R

You can consider leveraging popular library like moment.js http://momentjs.com/

您可以考虑利用像 moment.js 这样的流行库http://momentjs.com/

Then you can store date as YYYY-MM-DD in json and let moment handle the parsing:

然后你可以在 json 中将日期存储为 YYYY-MM-DD 并让 moment 处理解析:

var dateString = '2012-11-01';
var someday = moment(dateString);
var formattedDate = someday.format('ddd, DD MMM YYYY'); // 'Thu, 01 Nov 2012'

回答by Javi

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);

回答by xgc1986

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.

如果您想存储日期,我更愿意将其存储为格式类似于 yyyy/mm/dd hh:mm:ss 或类似格式的字符串,并在我想在 Date 对象中读取它时将其解析我需要的语言。

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.

我不明白你到底想要什么,使用 eval 方法(这是一个丑陋的做法),你可以添加一个方法来将实际日期放入对象中,并将自己添加到孩子中并调用添加到孩子中的方法。

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

PS如果要将其存储在文件中,则必须使用 eval 方法(不推荐)将方法存储为字符串或每次加载文件时执行

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)

您不能使用函数对 json 对象进行字符串化,因此,在添加方法 addDate 后的第二种方法中,我们将其从 json 对象中删除(您也可以删除 this.addDate,但我不知道它是否适用于 IE )

回答by cherit

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.

将此集合转换为 json 对象,然后在接收端将其转换回日期。您可以使用 joda 日期时间 API 进行转换。

回答by Fai Ng

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:

我在java中使用Gson来创建json输出,但是Gson不允许我将javascript函数放入json中。所以这就是我所做的:在要放置代码的位置使用替换标签(如前面的答案之一)。然后获取json的文本,替换标签,然后将文本保存到你的json文件中:

    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:

所以在使用这个json的时候,消费端就没什么可做的了。第一个输出是:

    {
      "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.

我对 json 的使用通常是将它保存为带有任务的 javascript,所以这对我有用。