How to save individual files per JSON array

muttBunch 100 Reputation points
2024-06-07T20:43:53.1233333+00:00

I am writing my own API to talk to CyberArk's API. I have one part complete where it imports a text file containing a list of safes per each line.

Example: "safeListFromCyberArk.txt"

  • PasswordManager
  • Test002
  • Test003

The method opens the txt file and reads each line to a string array. Each safeName from the txt file, is added into a list to retrieve account details based on that safeName.

public async Task<List<Accounts>> GetAccountDetailsFromSafeList()
{
    List<Accounts> acc = new List<Accounts>();
    foreach (var line in File.ReadLines("EPV-Data\\safeListFromCyberArk.txt"))
    {
        string[] safesInFile = line.Split('\t');
        var accounts = GetAccountDetailsFromSafe(safesInFile[0]);
        foreach (var account in await accounts)
        {

            acc.Add(new Accounts
            {
                id = account.id,
                name = account.name,
                address = account.address,
                safeName = account.safeName,
                userName = account.userName,
                password = account.password
            });

        }

    }
    //var safeCount = acc.GroupBy(x=>x.safeName).Count();
    //var ser = JsonConvert.SerializeObject(acc.GroupBy(x=>x.safeName));
    //File.WriteAllText($"EPV-Data\\{WOULD LIKE SAFE NAME AS THE FILENAME}.json", ser);

	return acc;
}

When I inspect the line...

var ser = JsonConvert.SerializeObject(acc.GroupBy(x=>x.safeName));

I can see that "ser" contains 3 JSON arrays, the first array, shows 3 accounts, and the other two arrays show 1 account each, which is correct, as it is grouped by the safeName.

What I'm trying to accomplish is, saving individual files with the account details, with the filename being the name of the current safeName that the array comes from. So my expected result would be:

"PasswordManager.json" - which would contain the JSON array for the 3 accounts for the safe "PasswordManager"

"Test002.json" - containing JSON array of 1 account for the safe "Test002"

"Test003.json" - containing JSON array of 1 account for the safe "Test003"

However, I am at a loss on how to do it. I'm assuming I would need to iterate over the arrays with a for loop and in there I would do the File.WriteAllText(...), but just not sure.

Any help would be appreciated.

Thanks

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,841 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,553 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 54,316 Reputation points
    2024-06-07T21:53:54.71+00:00

    If you're using JsonConvert then that means you're using Newtonsoft.Json. If this is a .NET 5+ app then you should really be using System.Text.Json instead. But we'll go with what you have now.

    While you could pick back apart the JSON after you've serialized, I think it is easier to break up your data into groups first and then serialize each group.

    var grouped = acc.GroupBy(x => x.safeName);
    foreach (var group in grouped)
    {
        var json = JsonConvert.SerializeObject(group.AsEnumerable());
    
        File.WriteAllText($"EPV-Data\\{group.Key}.json", json);
    };
    

    Since you're grouping by safeName and that is what you want to use for the filename then it is simply the group's key.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.