-1

I have a txt file:

orange : 1
blue : 2
yellow : 3

And i want to convert this file to json which look like that :

{ "colors-20220906" : {
     "orange" : 1,
     "blue" : 2,
     "yellow" : 3
  }
}

Add a key with a timestamp. Could you help me please, i'm blocked. Thank you

kgv34
  • 1
  • 1
  • The expected result isn't valid [Json](https://en.wikipedia.org/wiki/JSON) either, it requires comma's between the color properties – iRon Sep 06 '22 at 07:17
  • PowerShell 7: `@{ 'colors-20220906' = (Get-Content .\Your.txt |ConvertFrom-StringData -Delimiter ':') } |ConvertTo-Json` – iRon Sep 06 '22 at 07:21
  • Sorry, i forgot comma's. – kgv34 Sep 06 '22 at 10:34
  • { "colors-20220906" : { "orange" : 1, "blue" : 2, "yellow" : 3 } } – kgv34 Sep 06 '22 at 10:35
  • Please [edit](https://stackoverflow.com/posts/73617484/edit) and correct the information in there (rather than putting it in a difficult to read comment). – iRon Sep 06 '22 at 11:01

1 Answers1

2

In PowerShell 5 the ConvertFrom-StringData cmdlet does not have a Delimiter parameter and always uses the equals sign (=) as separator between the name and value of the input.

Also, ConvertFrom-StringData always returns a Hashtable, which is unordered by default.

$txt = Get-Content -Path 'TheFile.txt' -Raw
[PsCustomObject]@{'colors-20220906' = ($txt -replace ':', '=' | ConvertFrom-StringData )} | ConvertTo-Json

results in

{
    "colors-20220906":  {
                            "blue":  "2",
                            "yellow":  "3",
                            "orange":  "1"
                        }
}

If the order of subitems is important to you, you need to split the key:value lines yourself:

$txt  = Get-Content -Path 'TheFile.txt'
# create an ordered Hash to retain the order in which the items appear
$hash = [ordered]@{}  
foreach ($line in $txt) {
    $name,$value = ($line -split ':', 2).Trim()
    $hash[$name] = $value
}

[PsCustomObject]@{'colors-20220906' = $hash} | ConvertTo-Json

results in

{
    "colors-20220906":  {
                            "orange":  "1",
                            "blue":  "2",
                            "yellow":  "3"
                        }
}

P.S. PowerShell creates valid JSON, but the format is quite ugly. If you want to prettify that, you can use the function I posted earlier Format-Json

Theo
  • 57,719
  • 8
  • 24
  • 41