If I have some JSON like this:
$inputJson = @"
{
"attachments" :
[
{
"name": "attachment.eml",
"attachment_url": "https://www.attachment1.com"
},
{
"name": "attachment.eml",
"attachment_url": "https://www.attachment2.com"
},
{
"name": "attachment.eml",
"attachment_url": "https://www.attachment3.com"
}
]
}
where there is an attachments array and each element in that array has the same name but different URLs, how can I change all the names so that it outputs like this:
$outputJson = @"
{
"attachments" :
[
{
"name": "(attachment.eml)[1].eml",
"attachment_url": "https://www.attachment1.com"
},
{
"name": "(attachment.eml)[2].eml",
"attachment_url": "https://www.attachment2.com"
},
{
"name": "(attachment.eml)[3].eml",
"attachment_url": "https://www.attachment3.com"
}
]
}
"@
which renames each attachment to prevent duplicate names, but it preserves the URLs.
Ideally, the code would also make sure none of the new names already exist in the array as well. So if there is already an attachment named (attachment.eml)[1].eml in the array, it would handle that as well.
I've thought about somehow using Group-Object but I haven't quite figured out how to make that work.
Requesting for code is considered off-topic here. However, for self-training purposes, the following code snippet could do the job. Partially commented and itemized to (auxiliary) intermediate variables:
Result: