我有一个文本文件,其中包含近百万条json格式的记录。像
[{"ev":"AM","sym":"TMHC","v":1000,"av":74917,"op":18.92,"vw":19.1305,"o":19.13,"c":19.15,"h":19.15,"l":19.13,"a":19.143,"z":90,"n":1,"s":1549380300000,"e":1549380360000},{"ev":"AM","sym":"AAPL","v":7103,"av":184266,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}]
[{"ev":"AM","sym":"VB","v":213,"av":98285,"op":149.75,"vw":150.0575,"o":150.2104,"c":150.2104,"h":150.2104,"l":150.2104,"a":150.1944,"z":35,"n":1,"s":1549380300000,"e":1549380360000}]
所以我需要从包含AAPL的文件中找到json元素列表。就像我要通过AAPL一样,它必须提供整个文件中AAPL的json元素列表。
{"ev":"AM","sym":"AAPL","v":7103,"av":184266,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}
那我怎么找到它呢?我正在尝试为此使用JSONPATH,但是在JObject转换时,它给出了
之类的错误从JsonReader读取JObject时出错
我已为其应用以下代码:
const string filePath = @"D:\Aggregate_Minute_AAPL.json";
string text = System.IO.File.ReadAllText(filePath);
Newtonsoft.Json.Linq.JArray jsonArray = Newtonsoft.Json.Linq.JArray.Parse(text);
var json = Newtonsoft.Json.Linq.JObject.Parse(jsonArray.ToString());
var title = json.SelectToken("$.ev.sym[*]");
Console.WriteLine(title.First());
答案 0 :(得分:1)
您需要获取所有数组,而不管它们是全部还是一行,或者每个数组都位于换行符上,然后将每个数组解析为implementation 'androidx.core:core-ktx:1.0.1'
implementation 'androidx.appcompat:appcompat:1.0.2'
,然后使用所需键找到属性并获取该键的相应对象>
JArray
用法:
public static List<JObject> GetObjectByValue(string filePath, string matchValue)
{
var text = File.ReadAllText(filePath);
var pattern = @"\[(.*?)\]";
var matches = Regex.Matches(text, pattern);
var result = matches.Cast<Match>()
.Select(a => JArray.Parse(a.Value))
.Select(b => b.ToObject<JObject[]>())
.Where(x => x.Properties()
.Any(y => y.Name == "sym" && y.Value.ToString() == matchValue))
.FirstOrDefault()
.ToList();
return result;
}
编辑1:
如果您想使用var list_obj = GetObjectByValue(@"Path to your text file", "VB");
获取匹配对象,则可以使用以下函数,
Parallel.For
答案 1 :(得分:0)
由于文件很大,因此最好逐行读取而不是一次读取。
了解您的结构:每一行都是一个JSON数组,并且该数组有一个JSON对象。
// reading lines in loop
foreach (var line in System.IO.File.ReadLines(filePath))
{
// Parse the line into the array
JArray jsonArray = Newtonsoft.Json.Linq.JArray.Parse(line);
//parse the array into object,
//since each line has one object I have hardcoded the index to 0
//if there can be more objects in one array then will need to iterate
var json = JObject.Parse(jsonArray[0].ToString());
// access the token
var title = json["sym"]; // or json.SelectToken("sym");
Console.WriteLine(title.First());
}