node 读取json文件并处理

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

var walk = function(dir) {
	var results = []
	var list = fs.readdirSync(dir)
	list.forEach(function(file) {
    	// 排除static静态目录(可按你需求进行新增)
    	if (file === 'static') {
    		return false
    	}
    	file = dir + '/' + file
    	var stat = fs.statSync(file)
    	if (stat && stat.isDirectory()) {
    		results = results.concat(walk(file))
    	} else {
        	// 过滤后缀名(可按你需求进行新增)
        	if (path.extname(file) === '.json') {
        		results.push(path.resolve(__dirname, file))
        	}
        }
    })
	return results
}
function dealScri(arr) {

	arr.forEach(filepath => {
		var fileStr = fs.readFileSync(filepath, 'utf-8')
		var jsonstr = JSON.parse(fileStr);
		delete jsonstr['imageData']
		var shapesList = jsonstr["shapes"]
		for(var item in shapesList){
			if(typeof(shapesList[item])!="undefined"){
				var pointsList = shapesList[item]["points"]
				for(var points in pointsList){
					if(typeof(pointsList[points])!="undefined"){
						var pointsItemList=pointsList[points]
						for(var pointsItemIndex in pointsItemList){
							if(typeof(pointsItemList[pointsItemIndex])!="undefined"){
								pointsItemList[pointsItemIndex] = parseInt(pointsItemList[pointsItemIndex])
							}
						}

					}
				}
			}
		}

		jsonstr.xx=shapesList
		delete jsonstr['shapes']
		fs.writeFileSync(filepath, JSON.stringify(jsonstr,"","	"))
		console.log(filepath+" handler success")
	})
}

String.prototype.replaceAll = function (FindText, RepText) {
	return this.replace(new RegExp(FindText, "g"), RepText);
}
dealScri(walk(process.cwd()))

原文地址:https://www.cnblogs.com/blueberry006/p/14059646.html