go语言遍历文件夹并解析json文件

package main

import (
    "github.com/buger/jsonparser"
	"fmt"
	"log"
	"os"
	"io"
	"io/ioutil"
	"path"
)

var (
	files []string
)

//获取指定目录下的所有文件和目录
func TraverseDir(dirPth string) ( err error) {
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
	return  err
	}
	PthSep := string(os.PathSeparator)
	//suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写
	for _, fi := range dir {
		
		if fi.IsDir() { // 忽略目录
			TraverseDir(dirPth + PthSep + fi.Name())
		}else{
			files = append(files, dirPth+PthSep+fi.Name())
		}
	}
	return  nil
}

//解析json文件并检测需要字段用于计数
func ParserIWant(filePath string)(ret int64) {
	f, err := os.Open(filePath)
 	if err != nil {
		fmt.Println("File Open Error")
	 }else{
		 fmt.Println("File Open OK")
	 }
	line, err := ioutil.ReadAll(f)
	if err == io.EOF {
		fmt.Println("File Is Commplete")
	} else if err != nil {
		log.Fatal(err)
	}

	result, err := jsonparser.GetInt(line, "NocarInfo", "Tribike", "tribikeCount")
    if err != nil {
        fmt.Println(err)
	}
	if result == 1{
		return result
	}else{
		result, err := jsonparser.GetInt(line, "NocarInfo", "Motobike", "motobikeCount")
		if err != nil {
			fmt.Println(err)
		}
		if result == 1{
			return result
		}else{
			result, err := jsonparser.GetInt(line, "NocarInfo", "Bike", "bikeCount")
			if err != nil {
				fmt.Println(err)
			}
			if result == 1{
				return result
			}
		}
	}
	return 0
}

func main() {
	_ = TraverseDir("E:\\mvcode\\v2bufshool\\")
	var nVehicle int64
	for _, table1 := range files {
		fileSuffix := path.Ext(table1)
		fmt.Println(fileSuffix)
		if fileSuffix==".json"{
			ret := ParserIWant(table1)
			if ret == 1{
				nVehicle++
			}
		}
	}
	fmt.Printf("Has Vehicle:%d", nVehicle)
}

 

你可能感兴趣的:(go,go,json,travese)