Convert JSON to csv in C#

Convert JSON to csv in C#

  • Given users.json as the json file
using (var csv = new ChoCSVWriter("users.csv").WithFirstLineHeader())
{
   using (var json = new ChoJSONReader("users.json") 
      .WithField("Username")
      .WithField("Sub", jsonPath: "$.Attributes[?(@.Name == 'sub')].Value", isArray: true)
      .WithField("EmailVerified", jsonPath: "$.Attributes[?(@.Name == 'email_verified')].Value", isArray: true)
      .WithField("GivenName", jsonPath: "$.Attributes[?(@.Name == 'given_name')].Value", isArray: true)
      .WithField("FamilyName", jsonPath: "$.Attributes[?(@.Name == 'family_name')].Value", isArray: true)
      .WithField("Email", jsonPath: "$.Attributes[?(@.Name == 'email')].Value", isArray: true)
      .WithField("UserCreateDate")
      .WithField("UserLastModifiedDate")
      .WithField("Enabled")
      .WithField("UserStatus")
   )
{
   csv.Write(json);
}
}
Advertisement

Check if the string is valid JSON in C#

C# validate json string

public static bool IsJsonString(string str)
{
     if (string.IsNullOrWhiteSpace(str)) { return false; }
     str = str.Trim();
     if ((str.StartsWith("{") && str.EndsWith("}")) || 
         (str.StartsWith("[") && str.EndsWith("]")))
      {
         try
         {
            var obj = JToken.Parse(str);
            return true;
          }
          catch (JsonReaderException jex)
          {
             return false;
          }
          catch (Exception ex) //some other exception
          {
             return false;
          }
      }
      else
      {
         return false;
      }
 }

Export Users from Cognito in AWS

Export Cognito Users in AWS

As of today, there is no way to directly export users from Cognito in AWS.

But we can use AWS CLI or AWS SDK to get the list of users.

  • First step is to install AWS CLI on your machine

Click here to download and install AWS CLI

  • Next, step is to configure AWS on your machine. To do this, open cmd (command prompt) and do the following –
$ aws configure
AWS Access Key ID [None]: YourAccessKeyId
AWS Secret Access Key [None]: YourSecretAccessKey
Default region name [None]: YourRegion
Default output format [None]: json

Replace the above with your values. For more info, click here.

  • To get the list of all users in Cognito, run the following command
aws cognito-idp list-users --region <region> --user-pool-id <userPoolId> 
--output json > users.json

The above will return the list of users in a json format. If you want to get the result in a table format, run the following command

aws cognito-idp list-users --region <region> --user-pool-id <userPoolId>  --output table > users.txt
  • Now if you want to convert the result json to csv. Use the following code snippet.
private static void ConvertJsonToCsv()
{
 using (var csv = new ChoCSVWriter("users.csv").WithFirstLineHeader())
 {
   using (var json = new ChoJSONReader("CognitoUsers.json")
             .WithField("Username")
             .WithField("Email", jsonPath: "$.Attributes[?(@.Name == 
              'email')].Value", isArray: true)
             .WithField("UserStatus")
         )
  {
     csv.Write(json);
  }
 }
}

Rebuild examine index programmatically

Rebuild examine index

You can rebuild the examine index programmatically by using the following code –

ExamineManager.Instance.IndexProviderCollection["InternalIndexer"].RebuildIndex();
               

Interested in Cryptocurrency. Register and start investing here

Earn a side income by affiliate marketing. Learn here how to do it.

Combine one or more generic lists in C#

Combine one or more lists in C#

One or more generic lists can be combined or merged using zip() method in C#.

Below is an example of combining 4 lists by creating an extension method.

public static IEnumerable<TResult> ZipFour<T1, T2, T3, T4, TResult>(
            this IEnumerable<T1> source,
            IEnumerable<T2> second,
            IEnumerable<T3> third,
            IEnumerable<T4> fourth,
            Func<T1, T2, T3, T4, TResult> func)
        {
            using (var e1 = source.GetEnumerator())
            using (var e2 = second.GetEnumerator())
            using (var e3 = third.GetEnumerator())
            using (var e4 = fourth.GetEnumerator())
            {
                while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext() && e4.MoveNext())
                    yield return func(e1.Current, e2.Current, e3.Current, e4.Current);
            }
        }

Usage

list1.ZipFour(list2, list3, list4, (a, b, c, d) => new { A = a, B = b, C = c, D = d });

Interested in Cryptocurrency. Register and start investing here

Earn a side income by affiliate marketing. Learn here how to do it.

%d bloggers like this: