bluebox
bluebox

Reputation: 555

Querying JSON with SelectToken and LINQ

I have a bunch of financial data in json format and need to extract two pieces of information from it:

Here's the link to the data and below you can see what the data looks like in a json viewer:

enter image description here

Here's my latest (non-working) attempt to retrieve the industry names:

string url = "http://query.yahooapis.com/v1/public/yql?q=select%20%2A%20from%20yahoo.finance.industry%20where%20id%20in%20(select%20industry.id%20from%20yahoo.finance.sectors)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
string json = new WebClient().DownloadString(url);
JObject o = JObject.Parse(json);
IList<string> industries = o.SelectToken("query.results.industry").Select(s => (string)s).ToList();

How can I retrieve the ticker symbols and industry namesand store them in a convenient way (e.g. as string arrays or in a dictionary)?

Upvotes: 0

Views: 1259

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Looks like a Dictionary<string, IEnumerable<string>> might be well suited for this. If not, this should at least give you an idea of how to select the information you need:

Dictionary<string, IEnumerable<string>> industryData =
    o.SelectToken("query.results.industry")
        .ToDictionary(
            ind => ind["name"].ToString(),
            ind => ind["company"] != null ? 
                   ind["company"].Select(c => c["symbol"].ToString()) : null);

The conditional is necessary because there's (at least) one industry with zero companies (and no name for that matter). This will give you a dictionary who's keys are industry names and who's values are an IEnumerable<string> of stock tickers.

Upvotes: 2

Related Questions