Home > database >  How can I search a JSON file in C# by a key value, and then obtain a subsequent key value?
How can I search a JSON file in C# by a key value, and then obtain a subsequent key value?

Time:08-25

I have 3 JSON files that all contain the same data structure, however different data. The structure for all 3 files is as follows:

{
  "TokenId": "0",
  "rank": "2804"
},
{
  "TokenId": "1",
  "rank": "977"
},
{
  "TokenId": "2",
  "rank": "4085"
}

I am trying to create a new JSON file from these 3 files that has the following structure, and yes, they all have the same tokenID values, but slightly different rank values:

{
  "TokenId": "0",
  "File1Rank": "2804",
  "File2Rank": "2802",
  "File3Rank": "2809"
},
{
  "TokenId": "1",
  "File1Rank": "977",
  "File2Rank": "983",
  "File3Rank": "999"
},
{
  "TokenId": "2",
  "File1Rank": "4085",
  "File2Rank": "4089",
  "File3Rank": "4100"
}

How can I search by the tokenId value in each file to obtain the rank value? I can iterate through each valuea in each file to get both values, but I am struggling to create or update the new JSON correctly. The logic I feel I need is if the TokenId is equal to a certain value, then add the rank key/value, but I have not been able to find the answer on how I can do this.

CodePudding user response:

You can use the newtonsoft json library to parse and update the json files.

If your source file structure is:

{
  "Tokens": [
    {
      "TokenId": "0",
      "rank": "2804"
    },
    {
      "TokenId": "1",
      "rank": "977"
    },
    {
      "TokenId": "2",
      "rank": "4085"
    }
  ]
}

Pseudo code:

    using Newtonsoft.Json
    using Newtonsoft.Json.Linq
    void Main()
    {
        dynamic objFinal = JObject.Parse("{ 'Tokens':[] }");
        JArray finalArray = (JArray)objFinal["Tokens"];
        DirectoryInfo dir = new DirectoryInfo(@"D:\Projects\JsonFiles\");
        foreach(var file in dir.GetFiles("*.json"))
        {
            dynamic objJson = JObject.Parse(File.ReadAllText(file.FullName));
            JArray tokens = (JArray)objJson["Tokens"];
            foreach(JToken token in tokens)
            {           
                JToken searchResult = finalArray.Where(t=> Convert.ToString(t["TokenId"])==Convert.ToString(token["TokenId"])).FirstOrDefault();
                if(searchResult==null)
                {
                    //push new tokenid
                    JArray newFileRanks = new JArray();
                    newFileRanks.Add(token["rank"]);
                    dynamic newToken = new JObject();
                    newToken["TokenId"] = token["TokenId"];
                    newToken["fileRanks"] = newFileRanks;
                    finalArray.Add(newToken);
                }
                else
                {
                    //append to fileRanks
                    JArray existingFileRanks = (JArray)searchResult["fileRanks"];
                    dynamic fileRankExists = existingFileRanks.Where(t=> Convert.ToString(t)==Convert.ToString(token["rank"])).FirstOrDefault();
                    if(fileRankExists==null)
                    {
                        existingFileRanks.Add(token["rank"]);
                    }
                }
            }
        }
        Console.Write(JsonConvert.SerializeObject(objFinal));
    }

Final output:

{
  "Tokens": [
    {
      "TokenId": "0",
      "fileRanks": [ "2804", "2801" ]
    },
    {
      "TokenId": "1",
      "fileRanks": [ "977", "972" ]
    },
    {
      "TokenId": "2",
      "fileRanks": [ "4085", "4083" ]
    }
  ]
}
  • Related