Given a string []
array, you can convert it to a dictionary using LINQ, then serialize the dictionary.
E.g. using json.net:
var dictionary = array.AsPairs().ToDictionary(t => t.Key, t => t.Value);
var newJson = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
Demo fiddle #1 here.
Or, to serialize with system.text.json do:
var newJson = JsonSerializer.Serialize(dictionary, new JsonSerializerOptions { WriteIndented = true });
Demo fiddle #2 here.
Both options use the extension method:
public static class EnumerableExtensions
{
public static IEnumerable<(T Key, T Value)> AsPairs<T>(this IEnumerable<T> enumerable)
{
return AsPairsEnumerator(enumerable ?? throw new ArgumentNullException());
static IEnumerable<(T key, T value)> AsPairsEnumerator(IEnumerable<T> enumerable)
{
bool saved = false;
T key = default;
foreach (var item in enumerable)
{
if (saved)
yield return (key, item);
else
key = item;
saved = !saved;
}
}
}
}
And generate the result
{
"a": "b",
"c": "d",
"e": "f"
}