Home > Net >  how to get a value from json with just the index?
how to get a value from json with just the index?

Time:01-06

Im making an app which needs to loop through steam games. reading libraryfolder.vbf, i need to loop through and find the first value and save it as a string.

"libraryfolders"
{
    "0"
    {
        "path"      "D:\\Steam"
        "label"     ""
        "contentid"     "-1387328137801257092942"
        "totalsize"     "0"
        "update_clean_bytes_tally"      "42563526469"
        "time_last_update_corruption"       "1663765126"
        "apps"
        {
            "730"       "31892201109"
            "4560"      "9665045969"
            "9200"      "22815860246"
            "11020"     "776953234"
            "34010"     "11967809445"
            "34270"     "1583765638"

for example, it would record: 730 4560 9200 11020 34010 34270

Im already using System.Text.JSON in the program, is there any way i could loop through and just get the first value using System.Text.JSON or would i need to do something different as vdf doesnt separate the values with colons or commas?

CodePudding user response:

That is not JSON, that is the KeyValues format developed by Valve. You can read more about the format here:

https://developer.valvesoftware.com/wiki/KeyValues

There are existing stackoverflow questions regarding converting a VDF file to JSON, and they mention libraries already developed to help read VDF which can help you out.

VDF to JSON in C#

If you want a very quick and dirty way to read the file without needing any external library I would probably use REGEX and do something like this:

string pattern = "\"apps\"\\s {\\s (\"(\\d )\"\\s \"\\d \"\\s ) ";
string libraryPath = @"C:\Program Files (x86)\Steam\steamapps\libraryfolders.vdf";
string input = File.ReadAllText(libraryPath);

List<string> indexes = Regex.Matches(input, pattern, RegexOptions.Singleline)
   .Cast<Match>().ToList()
   .Select(m => m.Groups[2].Captures).ToList()
   .SelectMany(c => c.Cast<Capture>())
   .Select(c => c.Value).ToList();

foreach(string s in indexes)
{
    Debug.WriteLine(s);
}

See the regular expression explaination here: https://regex101.com/r/rSCvzy/1

It basically captures all occurances of "apps" { } in the 0 group, and does a repeating capture of pairs of numbers inbetween the curely brackets in the 1 group, but also captures the left most number in the pair of numbers in the 2 group. Generally repeating captures will only keep the last occurance but because this is C# we can still access the values.

The rest of the code takes each match, the 2nd group of each match, the captures of each group, and the values of those captures, and puts them in a list of strings. Then a foreach will print the value of those strings to log.

  • Related