isanka thalagala
isanka thalagala

Reputation: 476

Search text in JSON array in c#

I'm implementing simple search engine.all the data saved as a JSON in text file. My implementing scenario is,If I search word like 'rock' method should return result as list of tag Id's containing 'rock' value.I have been looking for sample codes but in every exsample they search by tag like track_id" but I need search by value. This is my sample JSON array ..

enter image description here

Test word : rock expected result : 991335,991336,991337

Upvotes: 1

Views: 2691

Answers (1)

Gergely Hamos
Gergely Hamos

Reputation: 411

I suggest to use a JSON library, like Json.net.

If you can allow to read the whole file, its super-easy with linq.

class TrackElement {
    public Track Track {get;set;}
}
class Track {
    public string track_id{get;set;}
    public string track_name{get;set;}
    public string track_category{get;set;}
}

Read file, deserialize and search:

var data = File.ReadAlltext("path/to/your/file.txt");
List<TrackElement> database = JsonConvert.DeserializeObject<List<TrackElement>>(data);

var results = database.Where(i=>i.Track.track_category.ToLower().Contains("rock")).Select(t=>t.Track.track_id);

If the database is real large, you should not read the whole stuff into memory, in this case you can use streamed parsing (token-by-token), reading the file directly. For this, you can use the JsonReader class from Json.net lib. (http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm)

Upvotes: 2

Related Questions