自定义行分隔符和json上的U-SQL自定义提取程序

问题描述 投票:0回答:2

我有几个文本文件具有以下数据结构:

{
huge 
json 
block that spans across multiple lines
}
--#newjson#--
{
huge 
json 
block that spans across multiple lines
}
--#newjson#--
{
huge 
json 
block that spans across multiple lines
} etc....

所以它实际上是由"--##newjson##--"字符串划分行的json块。我正在尝试编写一个客户提取器来解析它。问题是我不能使用string数据类型来提供json反序列化器,因为它的最大大小为128 KB,并且json块不适合这个。使用自定义提取器解析此文件的最佳方法是什么?

我尝试使用下面的代码,但它不起作用。甚至行分隔符"--#newjson#--"似乎也不正常。

public SampleExtractor(Encoding encoding, string row_delim = "--#newjson#--", char col_delim = ';')
{
    this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
    this._row_delim = this._encoding.GetBytes(row_delim);
    this._col_delim = col_delim;
}

public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{ 
    //Read the input  by json
    foreach (Stream current in input.Split(_encoding.GetBytes("--#newjson#--")))
    {
        var serializer = new JsonSerializer();

        using (var sr = new StreamReader(current))
        using (var jsonTextReader = new JsonTextReader(sr))
        {
            var jsonrow = serializer.Deserialize<JsonRow>(jsonTextReader); 
            output.Set(0, jsonrow.status.timestamp);
        }
        yield return output.AsReadOnly();
    }
} 
c# azure-data-lake u-sql
2个回答
0
投票

以下是如何实现解决方案:

1)创建一个与您的JSON对象等效的c#注意: - 假设您的所有json对象在文本文件中都相同。例如:

Json Code

{
        "id": 1,
        "value": "hello",
        "another_value": "world",
        "value_obj": {
            "name": "obj1"
        },
        "value_list": [
            1,
            2,
            3
        ]
    }

C#等价

 public class ValueObj
    {
        public string name { get; set; }
    }

    public class RootObject
    {
        public int id { get; set; }
        public string value { get; set; }
        public string another_value { get; set; }
        public ValueObj value_obj { get; set; }
        public List<int> value_list { get; set; }
    }

2)根据分隔符完成拆分后,更改下面的反序列化代码

using (JsonReader reader = new JsonTextReader(sr))
{
    while (!sr.EndOfStream)
    {
        o = serializer.Deserialize<List<MyObject>>(reader);
    }
}

这将反序列化c#类对象中的json数据,这将解决您的目的。稍后您可以再次序列化或以文本或...任何文件打印。

希望能帮助到你。


0
投票

你不需要自定义提取器来做到这一点。

最好的解决方案是逐行添加一个json。然后,您可以使用文本提取器并逐行提取。您也可以选择自己的分隔符。

REFERENCE ASSEMBLY [Newtonsoft.Json];
REFERENCE ASSEMBLY [Microsoft.Analytics.Samples.Formats];

    @JsonLines= 
        EXTRACT 
            [JsonLine] string
        FROM
            @Full_Path
        USING 
            Extractors.Text(delimiter:'\b', quoting : false);


@ParsedJSONLines = 
    SELECT 
        Microsoft.Analytics.Samples.Formats.Json.JsonFunctions.JsonTuple([JsonLine]) AS JSONLine
    FROM 
        @JsonLines

@AccessToProperties=
    SELECT 
        JSONLine["Property"] AS Property
    FROM 
        @ParsedJSONLines;
© www.soinside.com 2019 - 2024. All rights reserved.