Created
November 14, 2024 20:56
-
-
Save lornajane/de36857902bc2f6d7ad97c91472805c2 to your computer and use it in GitHub Desktop.
Parse a JSON file and run Vale on each string value
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 { exec } = require('child_process'); | |
const jsonSourceMap = require('json-source-map'); | |
const filePath = './input.json'; // Path to your JSON file | |
// Recursive function to process all string values with their locations | |
function processStringsWithLocations(json, pointerMap, processValue) { | |
if (typeof json === 'string') { | |
const pointer = pointerMap.json; | |
processValue(json, pointerMap.pointers[pointer]); | |
} else if (Array.isArray(json)) { | |
json.forEach((item, index) => { | |
processStringsWithLocations(item, { | |
json: `${pointerMap.json}/${index}`, | |
pointers: pointerMap.pointers, | |
}, processValue); | |
}); | |
} else if (typeof json === 'object' && json !== null) { | |
Object.entries(json).forEach(([key, value]) => { | |
processStringsWithLocations(value, { | |
json: `${pointerMap.json}/${key}`, | |
pointers: pointerMap.pointers, | |
}, processValue); | |
}); | |
} | |
} | |
// Function to check a string with an external command | |
function checkStringWithCommand(string, location) { | |
const command = `vale --output line "${string}"`; // command to run (with the string) | |
exec(command, (error, stdout, stderr) => { | |
if (error) { | |
console.error(`Error at line ${location.value.line}, column ${location.value.column}: ${string}`); | |
console.error(stdout.trim()); | |
return; | |
} | |
}); | |
} | |
// Main function to read JSON, parse with location data, and process strings | |
function main() { | |
fs.readFile(filePath, 'utf-8', (err, data) => { | |
if (err) { | |
console.error(`Error reading file: ${err.message}`); | |
return; | |
} | |
try { | |
const { data: json, pointers } = jsonSourceMap.parse(data); | |
processStringsWithLocations(json, { json: '', pointers }, (string, location) => { | |
checkStringWithCommand(string, location); | |
}); | |
} catch (parseError) { | |
console.error(`Error parsing JSON: ${parseError.message}`); | |
} | |
}); | |
} | |
main(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment