카테고리 없음

[C#] Json 파일을 CSV 파일로 변경하기

더월드 2023. 12. 16.

C# 특정 경로(서브 폴더 포함) 아래의 json 파일들을 한 개의 csv 파일로 변경하기

C#에서 특정 경로와 서브 폴더에서 모든 JSON 파일을 읽어와 CSV 파일로 변경하는 코드입니다.

Newtonsoft.Json 라이브러리를 사용하여 JSON을 CSV로 변환합니다.

먼저, NuGet 패키지 관리자 콘솔에서 Newtonsoft.Json을 설치해야 합니다.

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

class Program
{
    static void Main()
    {
        string sourceFolderPath = @"path\to\your\source\folder";
        string targetCsvFilePath = @"path\to\your\target\output.csv";

        ConvertJsonFilesToCsv(sourceFolderPath, targetCsvFilePath);
    }

    static void ConvertJsonFilesToCsv(string sourceFolder, string targetCsvFilePath)
    {
        try
        {
            // 리스트를 사용하여 모든 JSON 파일의 데이터를 저장
            List<string[]> csvData = new List<string[]>();

            // 폴더 내의 모든 파일을 대상으로 처리
            foreach (var filePath in Directory.GetFiles(sourceFolder, "*.json", SearchOption.AllDirectories))
            {
                // JSON 파일 읽기 (라인별로 읽기)
                string[] jsonLines = File.ReadAllLines(filePath);
				
                foreach (var jsonLine in jsonLines)
                {
                    // JSON 데이터 추출
                    var data = JsonConvert.DeserializeObject<YourDataClass>(jsonLine);
				
                    // JSON 데이터를 CSV 행으로 변환
                    string[] csvRow = GetPropertyValues(data);
				
                    // CSV 데이터 리스트에 추가
                    csvData.Add(csvRow);
                }
            }

            // CSV 파일에 쓰기
            WriteCsvFile(targetCsvFilePath, csvData);

            Console.WriteLine($"모든 파일이 성공적으로 변환되었습니다. CSV 파일 경로: {targetCsvFilePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"오류 발생: {ex.Message}");
        }
    }

    static void WriteCsvFile(string csvFilePath, List<string[]> csvData)
    {
        // CSV 파일에 쓸 내용을 저장할 리스트
        List<string> lines = new List<string>();

        // 헤더 라인 작성 (첫 번째 JSON 파일의 속성 이름을 기준으로 함)
        lines.Add(string.Join(",", GetPropertyNames(csvData[0])));

        // 데이터 라인 작성
        foreach (var row in csvData)
        {
            lines.Add(string.Join(",", row));
        }

        // CSV 파일에 쓰기
        File.WriteAllLines(csvFilePath, lines);
    }

    static List<string> GetPropertyNames(string[] csvRow)
    {
        return new List<string>(csvRow);
    }

    static string[] GetPropertyValues(JObject jsonObject)
    {
        return jsonObject.Properties().Select(property => property.Value.ToString()).ToArray();
    }
}

 

json 파일에서 특정 부분만 csv 파일로 변경하기

이 코드는 주어진 JSON 데이터를 처리하고 "awsRegion, eventCategory, eventID, filename" 값을 CSV 파일로 추출합니다. 

JSON 구조에 따라 YourDataClass 클래스와 필요한 내용을 추출하는 부분을 조정하여 사용하세요.

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        string folderPath = "경로\\폴더"; // 여기에 대상 폴더의 경로를 입력하세요
        string csvFilePath = "출력\\파일\\경로\\output.csv"; // 여기에 CSV 파일을 저장할 경로를 입력하세요

        // 폴더 내 JSON 파일들을 찾아서 처리
        ProcessJsonFiles(folderPath, csvFilePath);

        Console.WriteLine("작업이 완료되었습니다.");
    }

    static void ProcessJsonFiles(string folderPath, string csvFilePath)
    {
        var records = new List<YourDataClass>(); // YourDataClass에는 JSON 파일에서 추출할 데이터의 형식이 들어갑니다.

        // 폴더 내 모든 JSON 파일을 검색
        var jsonFiles = Directory.EnumerateFiles(folderPath, "*.json", SearchOption.AllDirectories);       
        
        foreach (var jsonFile in jsonFiles)
        {
            // JSON 파일 읽기
            //string jsonContent = File.ReadAllText(jsonFile);

            // JSON 파일 읽기 (라인별로 읽기)
            string[] jsonLines = File.ReadAllLines(filePath);

            foreach (var jsonLine in jsonLines)
            {
                // JSON 데이터 추출
                var data = JsonConvert.DeserializeObject<YourDataClass>(jsonLine);

                // 필요한 값만 추출하여 리스트에 추가
                var extractedData = new ExtractedData
                {
                    AwsRegion = data.AwsRegion,
                    EventCategory = data.EventCategory,
                    EventID = data.EventID,
                    Filename = data.Filename
                };

                records.Add(extractedData);
            }
        }

        // CSV 파일에 쓰기
        using (var writer = new StreamWriter(csvFilePath))
        {
            // CSV 파일의 헤더 작성
            writer.WriteLine("Title,Value"); // CSV 파일의 각 열의 헤더를 작성, 필드 구분자로 쉼표 사용

            // 각 레코드를 CSV 파일에 작성
            foreach (var record in records)
            {
                writer.WriteLine($"{record.Title},{record.Value}");
                // 필요한 만큼 더 많은 속성을 추가
            }
        }
    }

    // YourDataClass의 예시
    public class YourDataClass
    {
        public string AwsRegion { get; set; }
        public string EventCategory { get; set; }
        public string EventID { get; set; }
        public string EventName { get; set; }
        public string EventSource { get; set; }
        public string EventTime { get; set; }
        public string EventType { get; set; }
        public string EventVersion { get; set; }
        public bool ManagementEvent { get; set; }
        public bool ReadOnly { get; set; }
        public string RecipientAccountId { get; set; }
        public string RequestID { get; set; }
        public RequestParameters RequestParameters { get; set; }
        public string SourceIPAddress { get; set; }
        public string UserAgent { get; set; }
        public UserIdentity UserIdentity { get; set; }
        public TlsDetails TlsDetails { get; set; }
        public string Filename { get; set; }
    }

    public class RequestParameters
    {
        public string InstanceName { get; set; }
    }

    public class UserIdentity
    {
        public string AccessKeyId { get; set; }
        public string AccountId { get; set; }
        public string Arn { get; set; }
        public string PrincipalId { get; set; }
        public string Type { get; set; }
    }

    public class TlsDetails
    {
        public string TlsVersion { get; set; }
        public string CipherSuite { get; set; }
        public string ClientProvidedHostHeader { get; set; }
    }

    // 추출된 데이터 클래스
    public class ExtractedData
    {
        public string AwsRegion { get; set; }
        public string EventCategory { get; set; }
        public string EventID { get; set; }
        public string Filename { get; set; }
    }
}

 

댓글

💲 추천 글