Advertisement
goodwin64

Count how many strings are in .json file

Mar 26th, 2022
1,456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // jsonchecker.js
  2. // run as "node jsonchecker.js"
  3.  
  4. const fs = require('fs')
  5.  
  6. const testFolder = '.'
  7.  
  8. const jsonFiles = fs.readdirSync(testFolder).filter((f) => f.endsWith('.json'))
  9.  
  10. function countStrings(json) {
  11.     return Object.keys(json).reduce((acc, currKey) => {
  12.         const currVal = json[currKey]
  13.         if (typeof currVal === 'string') {
  14.             return acc + 1
  15.         } else {
  16.             return acc + countStrings(currVal)
  17.         }
  18.     }, 0)
  19. }
  20.  
  21. jsonFiles.forEach((f) => {
  22.     let rawdata = fs.readFileSync(f)
  23.     let jsonContent = JSON.parse(rawdata)
  24.     const strings = countStrings(jsonContent)
  25.     console.log(`file: ${f.toString().padStart(40)}, strings: ${strings}`)
  26. })
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement