如何按日期对JSON进行排序?

3
我正在尝试遍历JSON并按日期排序,以便查看最新日期至最旧日期,然后将其写入文件。
以下是我的代码:
var reader = JSON.parse(fs.readFileSync('txt.json', 'utf8'));
function sortByDate(a, b) {
    return new Date(a.lastUpdated).toJSON() - new Date(b.lastUpdated).toJSON();
}

reader.sort(sortByDate)

JSON数据示例

{
    "Data": {
        "Contents": [
            {
                "Key": [
                    "HelloTest"
                ],
                "lastUpdated": [
                    "2019-10-25T10:30:50.558Z"
                ]
            },
            {
                "Key": [
                    "TestHello"
                ],
                "lastUpdated": [
                    "2019-03-26T10:30:50.558Z"
                ]
            }
        ]
    }
}



Key and lastUpdated are collections in your json so I think you should try a.lastUpdated[0] and b.lastUpdated[0] - Chetan
类型错误:reader.sort 不是一个函数,这就是我得到的错误。 - Cameron Shearer
https://dev59.com/XXNA5IYBdhLWcg3wZ85R - Chetan
你能否更新问题并附上你最新的代码? - Chetan
2个回答

2

以下是我在您的代码中发现的几个错误:

  • 您的函数名称有一个拼写错误,应该是sortByDate而不是sortbyDate
  • 您需要对内部的json.Data.Contents数组进行排序,而不是外部的json对象。
  • 您需要使用lastUpdated[0]引用您的lastUpdated数组的第一个元素。
  • 最后,在您的排序函数中,您不需要调用toJSON()来转换日期对象,只需转换为日期并返回差异即可。

此外,您的内部数据字段是数组,这对于KeylastUpdated值来说似乎很奇怪。

如果您保留字段作为数组,以下是一个工作示例,显示如何按日期排序内部的Data.Contents数组:

const jsonString = `{
  "Data": {
    "Contents": [{
        "Key": ["HelloTest"],
        "lastUpdated": ["2019-10-25T10:30:50.558Z"]
      }, {
        "Key": ["TestHello"],
        "lastUpdated": ["2019-03-26T10:30:50.558Z"]
      }]
  }
}`;

function sortByDate(a, b) {
    return new Date(a.lastUpdated[0]) - new Date(b.lastUpdated[0]);
}

const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };

console.log(output);

如果您将字段更改为标量(我建议这样做),这里有另一个例子:最初的回答。

const jsonString = `{
  "Data": {
    "Contents": [{
        "Key": "HelloTest",
        "lastUpdated": "2019-10-25T10:30:50.558Z"
      }, {
        "Key": "TestHello",
        "lastUpdated": "2019-03-26T10:30:50.558Z"
      }]
  }
}`;

function sortByDate(a, b) {
    return new Date(a.lastUpdated) - new Date(b.lastUpdated);
}

const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };

console.log(output);


1
太好了!我正在使用一个旧的XML文件,通过编写一个函数将其转换为JSON格式,感谢您的帮助,现在我明白了我所犯的错误。 - Cameron Shearer
1
比将其转换为日期更简洁的方法是仅测试 a.lastUpdated < b.lastUpdated ? -1 : a.lastUpdated > b.lastUpdated ? 1 : 0。没有必要进行所有这些 Date 转换。 - Scott Sauyet

0

看起来你正在从文件中读取内容,然后需要按日期排序,最后将其写入新文件。如果这是你想要的,以下内容应该会有所帮助:

const fs = require('fs');
const path = require('path');

// JSON files can be requied in as objects without parsing
// `arrayOfStuff` will be the var name for `Contents`
const { Data: { Contents: arrayOfStuff } } = require('./data.json');

function sortByDate(el1, el2) {
  // access the date from the object and turn into date object
  let date1 = new Date(el1.lastUpdated[0]);
  let date2 = new Date(el2.lastUpdated[0]);
  // compare date objects in revers order to get newest to oldest
  return (date2 - date1);
}

// sort `Contents` from the `Data` object and turn into JSON
const sortedContent = arrayOfStuff.sort(sortByDate);
const newDataObj = JSON.stringify({ Data: { Content: sortedContent }}, null, 2);

// create the fully qualified file path with `sortedByDate.json` as the file name
const filePath = path.resolve('./', 'sortedByDate.json');

// write to new file
fs.writeFile(filePath, newDataObj, (err) => {
  if(err) {
    console.log('Made an oopsie:', err);
  }
    console.log(`Success!, new JSON file located at: ${filePath}`);
}); // write to file

好的,我已经尝试过了,但是我的JSON文件名叫做images.json,它返回了“找不到模块./images.json”的错误信息。 - Cameron Shearer
通常在文件路径错误时会出现该错误消息。我建议您再次检查images.json的位置,确认相对于脚本运行的文件所在的位置是否正确。 - Maumasi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接