3

I'm trying to loop through a JSON and sort it by the date so I can see the latest date to the oldest date, and then write it to the file.

Here is my code

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 Example

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


Cameron Shearer
  • 142
  • 1
  • 10

2 Answers2

2

Here are a couple of errors I found in your code:

  • Your function name has a typo, it should be sortByDate and not sortbyDate.
  • You need top sort the inner json.Data.Contents array, not the outer json object.
  • You need to reference the first element of your lastUpdated arrays using lastUpdated[0].
  • Finally, you do not need to call toJSON() on the date objects in your sorting function, simply convert to date and return the difference.

Also your inner data fields are arrays, which seems strange for a Key and a lastUpdated value.

If you keep your fields as arrays, here is a working example showing how to sort the inner Data.Contents array by date:

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

If you change your fields to scalars, which I suggest, here is another example:

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);
jo_va
  • 13,504
  • 3
  • 23
  • 47
  • 1
    **Perfect!** I'm using an old XML file that I had to convert to a JSON by making a function, thanks for the help I understand the errors I have made now. – Cameron Shearer Aug 25 '19 at 02:06
  • 1
    Cleaner than converting to a date is to just test `a.lastUpdated < b.lastUpdated ? -1 : a.lastUpdated > b.lastUpdated ? 1 : 0`. No reason to do all those `Date` conversions. – Scott Sauyet Aug 25 '19 at 02:06
0

It looks like you're reading contents from a file, then needs to sort it by date, and then finally write it to a new file. If that is what you're going for, the following should help:

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
Maumasi
  • 26
  • 4
  • Ok I've tried this however my JSON is called images.json and it's returning `can't find module ./images.json` – Cameron Shearer Aug 25 '19 at 03:00
  • You would normally get that error message when the file path is incorrect. I would double-check where the `images.json` is located from the relative file from where your script is running. – Maumasi Aug 25 '19 at 03:45