简体   繁体   English

从json创建一个csv文件,每条记录具有不同的标头值

[英]Creating a csv file from json with different header values per record

I have a massive json file that is very nested. 我有一个非常嵌套的海量json文件。 I need to write the multiple csv files depending on the name of a certain field, if it exists then add the values to the headers I've created if it does not then create a new one. 我需要根据某个字段的名称编写多个csv文件,如果存在,则将值添加到我创建的标头中(如果它不创建新标头)。 This is working just fine. 这很好用。 However I have ran into a problem where the headers do not match because this particular header doesn't exist for that record. 但是我遇到了一个标题不匹配的问题,因为该记录不存在该特定的标题。 Example: 例:

Header:  Dog   Cat  Mouse  Horse
Record1:  yes   yes  yes   yes

// above is an example of a file with all values Adding record Two where a header value is not listed at all //上面是具有所有值的文件的示例添加记录2,但其中的头值根本没有列出

Header:  Dog   Cat  Mouse  Horse
Record1:  yes   yes  yes   yes
Record2:  yes   yes  yes   ***

Record2 above does not have a mouse on the record but because it doesn't line up the yes shifted left. 上面的Record2在记录上没有鼠标,但是因为它没有排列在左移的yes上。 I need to write a Null under than header before spitting out the values to the file. 我需要在标头下写一个Null,然后才能将值分散到文件中。 Below is my code if you could help that would be great as I'm lost at this point: 下面是我的代码,如果您可以帮助的话,那会很好,因为此时我迷路了:

        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;
        }
    }

My horrific json file that I cannot change as its used by my company: https://codeshare.io/rGL6K5 我无法更改公司使用的可怕的json文件: https : //codeshare.io/rGL6K5

Is there some kind of pattern? 有某种模式吗? Reason I am asking is, maybe you could create a service that serialize the JSON to a complex object(s). 我问的原因是,也许您可​​以创建一个将JSON序列化为复杂对象的服务。 Once that is done have a service that serializes that object to csv. 一旦完成,就有一个服务可以将该对象序列化为csv。 The service would know to write multiple csv files as needed. 该服务将知道根据需要写入多个csv文件。

I'd stay away from using {dynamic}, if there is a reliable pattern to the JSON. 如果JSON有可靠的模式,我将不使用{dynamic}。 I'd get a sample JSON file, copy it into the clipboard and using the Paste JSON to Classes feature in Visual Studio. 我将得到一个示例JSON文件,将其复制到剪贴板中,并使用Visual Studio中的“将JSON粘贴到类”功能。

https://blogs.msdn.microsoft.com/webdev/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc/ https://blogs.msdn.microsoft.com/webdev/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc/

After that, deserialize it with Newtonsoft.JSON into a nice reliable object from which to build your CSV. 之后,使用Newtonsoft.JSON将其反序列化为一个不错的可靠对象,从中可以构建CSV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM