【发布时间】:2015-10-03 07:12:42
【问题描述】:
我正在尝试将非常大的 JSON 文件拆分为给定数组的较小文件。例如:
{
"headerName1": "headerVal1",
"headerName2": "headerVal2",
"headerName3": [{
"element1Name1": "element1Value1"
},
{
"element2Name1": "element2Value1"
},
{
"element3Name1": "element3Value1"
},
{
"element4Name1": "element4Value1"
},
{
"element5Name1": "element5Value1"
},
{
"element6Name1": "element6Value1"
}]
}
...向下到 { "elementNName1": "elementNValue1" } 其中 N 是一个大数
用户提供代表要拆分的数组的名称(在本例中为“headerName3”)和每个文件的数组对象数,例如1,000,000
这将产生 N 个文件,每个文件都包含顶部名称:值对(headerName1、headerName3)和每个文件中最多 1,000,000 个 headerName3 对象。
我正在使用出色的 Newtonsof JSON.net,并且了解我需要使用流来执行此操作。
到目前为止,我已经查看了 JToken 对象的读数,以确定在读取令牌时 PropertyName == "headerName3" 发生的位置,但我想要做的是读取数组中每个对象的整个 JSON 对象并且不必继续将 JSON 解析为 JToken;
这是我目前正在构建的代码的 sn-p:
using (StreamReader oSR = File.OpenText(strInput))
{
using (var reader = new JsonTextReader(oSR))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
intObjectCount++;
}
else if (reader.TokenType == JsonToken.EndObject)
{
intObjectCount--;
if (intObjectCount == 1)
{
intArrayRecordCount++;
// Here I want to read the entire object for this record into an untyped JSON object
if( intArrayRecordCount % 1000000 == 0)
{
//write these to the split file
}
}
}
}
}
}
我不知道——事实上,也不关心——JSON 本身的结构,对象在数组中可以是不同的结构。因此,我没有对类进行序列化。
这是正确的方法吗? JSON.net 库中是否有一组方法可以轻松用于执行此类操作?
任何帮助表示赞赏。
【问题讨论】:
-
您确定要拆分的数组值属性将是根 JSON 对象中的 last 项吗? JSON standard 声明,“object 是一组无序的名称/值对”,因此原则上要拆分的属性不必排在最后。
-
到目前为止,供应商已经给出了将数组作为最后一个对象的文件。由于我正在阅读流,我相信它将是顶层的最后一个对象。但是,是的,用更一般的术语来说,我不会依赖这个。我已经为较小的文件编写了另一个版本,它克隆了原始 JSON,然后用原始 JSON 的子集替换指定的数组。