Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

Convert JSON Arrays into batches of JSON Arrays using the LINQ Chunk method

$
0
0

This is one way of converting a JSON array of any JSON objects into batches. This function uses the LINQ Chunk method to convert a 1 dimensional array input into a 2 dimensional array output:

Example input array:

[
    { "a": "1" },
    { "a": "2" },
    { "a": "3" },
    { "a": "4" },
    { "a": "5" },
    { "a": "6" },
    { "a": "7" }
]

Converted into batches of 3:

[
    [
        {"a":"1"},
        {"a":"2"},
        {"a":"3"}
    ],
    [
        {"a":"4"},
        {"a":"5"},
        {"a":"6"}
    ],
    [
        {"a":"7"}
    ]
]

THE CODE:

using System;
using System.Collections.Generic;
using System.Linq;

// For demo purpose: Grab a Json array and convert it into an array of objects
string jsonInputString = "[ { \"a\": \"1\" }, { \"a\": \"2\" }, { \"a\": \"3\" }, { \"a\": \"4\" }, { \"a\": \"5\" }, { \"a\": \"6\" }, { \"a\": \"7\" } ]";
List<object> jsonInput = System.Text.Json.JsonSerializer.Deserialize<List<object>>(jsonInputString);

// Create a new list of objects, and use the Chunk method to create batches
// of a certain size
List<object> batch = new List<object>();
foreach (var chunk in jsonInput.Chunk(3))
{
  batch.Add(chunk);
}

// For demo purposes, convert the batched objects as a Json string
string jsonOutputString = System.Text.Json.JsonSerializer.Serialize(batch);

// Output the contents
Console.WriteLine(jsonOutputString);

When using the Chunk method, C# does the heavy lifting of breaking the array into batches of a maximum size.

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles