Created
May 31, 2023 18:09
-
-
Save jeroensmink98/7802c287829df1a356d8b14de7a8d60a to your computer and use it in GitHub Desktop.
Parse data from a Polarsteps trip.json and create a new JSON out of it with parsed dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const jsonString = fs.readFileSync('./assets/trip.json', 'utf8'); | |
// Parse the JSON string into an object | |
const data = JSON.parse(jsonString); | |
const locations = []; | |
let index = 1; | |
// Loop over the items in the "all_steps" array | |
data.all_steps.forEach((step) => { | |
// Access the location properties of each step object | |
const locationId = step.location_id; | |
const locationName = step.location.name; | |
const locationDetail = step.location.detail; | |
const countryCode = step.location.country_code; | |
const latitude = step.location.lat; | |
const longitude = step.location.lon; | |
// Extract the weather properties | |
const weatherCondition = step.weather_condition; | |
const weatherTemperature = step.weather_temperature; | |
// Convert the start_time and end_time timestamps | |
const startTime = convertTimestamp(step.start_time); | |
const endTime = convertTimestamp(step.end_time); | |
const newStep = { | |
index, | |
locationId, | |
locationName, | |
locationDetail, | |
countryCode, | |
latitude, | |
longitude, | |
weatherCondition, | |
weatherTemperature, | |
startTime, | |
endTime, | |
}; | |
index++; | |
locations.push(newStep) | |
// Do something with the location data | |
console.log(`Location ID: ${locationId}`); | |
console.log(`Location Name: ${locationName}`); | |
console.log(`Location Detail: ${locationDetail}`); | |
console.log(`Country Code: ${countryCode}`); | |
console.log(`Latitude: ${latitude}`); | |
console.log(`Longitude: ${longitude}`); | |
console.log(`Weather Condition: ${weatherCondition}`); | |
console.log(`Weather Temperature: ${weatherTemperature}`); | |
console.log(`Start Time: ${startTime}`); | |
console.log(`End Time: ${endTime}`); | |
console.log('---'); | |
}); | |
function convertTimestamp(timestamp) { | |
if (timestamp) { | |
const date = new Date(timestamp * 1000); // Convert seconds to milliseconds | |
return date.toISOString(); // Returns the date in ISO 8601 format | |
} | |
return null; | |
} | |
// Convert the new array to JSON format | |
const json = JSON.stringify(locations, null, 2); | |
// Write the new JSON string to a file | |
fs.writeFileSync('parsed-trip.json', json, 'utf8'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment