I'm trying to add the length of an UTF-8 string as a new value pair to the following JSON file:
{
"uuid": "6f74b1ba-0d7c-4c85-955b-2a4309f0e8df",
"records": {
"record1": [{
"locale": "en_US",
"category": "alpha",
"contents": "My hovercraft is full of eels"
}
],
"record2": [{
"locale": "cs_CZ",
"category": "alpha",
"contents": "Moje vznášedlo je plné úhořů"
}
],
"record3": [{
"locale": "es_ES",
"category": "alpha",
"contents": "Mi aerodeslizador está lleno de anguilas"
}
]
}
}
using the following code:
$infile = "C:\Temp\input.json"
$outfile = "C:\Temp\output.json"
$json = Get-Content $infile -Encoding UTF8 | ConvertFrom-Json
$records = $json.records
$records.PSObject.Properties | ForEach-Object {
$length = $_.Value.contents.length
$_.Value | Add-Member -Type NoteProperty -Name 'length' -Value $length
}
$json | ConvertTo-Json | Out-File $outfile -Encoding UTF8
The code seems to work, but when I output the file I get this, which looks like PowerShell code, not a JSON file.
{
"uuid": "6f74b1ba-0d7c-4c85-955b-2a4309f0e8df",
"records": {
"record1": [
"@{locale=en_US; category=alpha; contents=My hovercraft is full of eels; length=29}"
],
"record2": [
"@{locale=cs_CZ; category=alpha; contents=Moje vznášedlo je plné úhořů; length=28}"
],
"record3": [
"@{locale=es_ES; category=alpha; contents=Mi aerodeslizador está lleno de anguilas; length=40}"
]
}
}
But I want to get this:
{
"uuid": "6f74b1ba-0d7c-4c85-955b-2a4309f0e8df",
"records": {
"record1": [{
"locale": "en_US",
"category": "alpha",
"contents": "My hovercraft is full of eels",
"length": 29
}
],
"record2": [{
"locale": "cs_CZ",
"category": "alpha",
"contents": "Moje vznášedlo je plné úhořů",
"length": 28
}
],
"record3": [{
"locale": "es_ES",
"category": "alpha",
"contents": "Mi aerodeslizador está lleno de anguilas",
"length": 40
}
]
}
}
What part of my code do I need to change?
............................................................ ............................................................ ............................................................