非常にネストされた大量のjsonファイルがあります。特定のフィールドの名前に応じて複数のcsvファイルを作成し、それが存在する場合は、作成したヘッダーに値を追加してから、新しいフィールドを作成します。これはうまくいきます。しかし、私はこの特定のヘッダーがそのレコードのために存在しないため、ヘッダーが一致しない問題に遭遇しました。例://上記レコードごとに異なるヘッダー値を持つjsonからcsvファイルを作成する
Header: Dog Cat Mouse Horse
Record1: yes yes yes yes
は、上記にマウスを持っていないヘッダの値は、すべて
Header: Dog Cat Mouse Horse
Record1: yes yes yes yes
Record2: yes yes yes ***
RECORD2に記載されていないレコードつの追加すべての値 持つファイルの例でありますレコードがありますが、それは左にシフトしたイエスを整列していないからです。私は、ファイルに値を吐き出す前に、ヘッダーの下にNullを書く必要があります。あなたは私はこの時点で迷ってしまいましたとしてそれは素晴らしいことだ助けることができる場合は、以下の私のコードです:
static List<string> headList = new List<string>();
static List<string> newHeaderList = new List<string>();
static List<string> valueList = new List<string>();
static List<string> oldHeadList = new List<string>();
static void Main()
{
var data = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(
@"C:\Users\nphillips\workspace\2016R23\UITestAutomation\SeedDataGenerator\src\staticresources\seeddata.resource"));
string fileName = "";
var bundles = data.RecordSetBundles;
foreach (var bundle in bundles)
{
var records = bundle.Records;
foreach (var record in records)
{
var test = record.attributes;
foreach (var testagain in test)
{
// Getting the object Name Ex. Location, Item, etc.
var jprop = testagain as JProperty;
if (jprop != null)
{
fileName = jprop.First.ToString().Split('_')[2] + ".csv";
}
break;
}
string header = "";
string value = "";
foreach (var child in record)
{
var theChild = child as JProperty;
if (theChild != null && !theChild.Name.Equals("attributes"))
{
// adding the name and values to list
headList.Add(child.Name);
valueList.Add(child.Value.ToString());
}
}
// calling method to write columns and values
writeCSV(headList, valueList, fileName);
valueList.Clear();
headList.Clear();
}
}
}
public static void writeCSV(List<string> headList, List<string> valList, string fileName)
{
string headerString = "";
string value = "";
if (!File.Exists(fileName))
{
foreach (var header in headList)
{
foreach (var val in valList)
{
value += val + ",";
}
oldHeadList.Add(header);
headerString += header + ',';
}
headerString += "+" + Environment.NewLine;
File.WriteAllText(fileName, headerString);
}
else
{
foreach (var header in headList)
{
foreach (var oldHeader in oldHeadList)
{
foreach (var val in valList)
{
if (header != oldHeader)
{
value += "null,";
}
else
{
value += val + ",";
}
}
}
}
}
File.AppendAllText(fileName, value);
value += Environment.NewLine;
}
}
その私の会社で使用されるように、私は変更することはできません私の恐ろしいJSONファイル:https://codeshare.io/rGL6K5