0

I have a lot of JSON format data into text file and format is like:

[{"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":"SPYG","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":"AAPL","v":73,"av":1866,"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}]

So I need to find json element of particular symbol. Like if I use AAPL then it gives us all AAPL element data from txt file. Like

{"ev":"AM","sym":"AAPL","v":73,"av":1866,"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}

So please can you help me to how should I make it ?

static void xPathUsing()
{
  const string filePath = @"D:\Aggregate_Minute_AAPL.txt";
  using (StreamReader r = new StreamReader(filePath))
  {
      string json = r.ReadToEnd();
  }
}
dpapadopoulos
  • 1,834
  • 5
  • 23
  • 34
Hardik Dhankecha
  • 148
  • 1
  • 11

1 Answers1

0

As you need to run multiple operations on the data, the best way would be to read the data into memory once (or again whenever the data changes) and hold them in a way that supports fast querying. In order to find a row by the symbol, you could create a dictionary that holds the data.

The following samples use the widely used JSON.NET library for parsing the JSON.

First, you need to define a class that ressembles the schema of your JSON objects, e.g.:

class Row
{
    [JsonProperty("sym")]
    public string Symbol { get; set; }
    public decimal vw { get; set; }
    // ...
}

Please note that you can use the JsonProperty attribute in order to be able to assign different names to the properties of the class than in the JSON.

The following sample shows how to read the data from a file and how to convert it to a dictionary:

var input = File.ReadAllText("C:\\Temp\\abc.json");
var rows = JsonConvert.DeserializeObject<IEnumerable<Row>>(input);
var dict = rows.ToDictionary(x => x.Symbol, x => x, StringComparer.OrdinalIgnoreCase);

After preparing your dictionary once, you can get the corresponding row by using the indexer:

var aaplRow = dict["AAPL"];
Markus
  • 20,838
  • 4
  • 31
  • 55