简体   繁体   中英

Convert a txt file to json file with powershell

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

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"
                        }
}

PS 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM