Reputation: 4646
Perhaps it's easy question and will be banned but I spend hours today and not make it work as I expected. so I have such object:
data_1 data_2 ... abra_12 ...
I want convert it into json like this:
[
{"data_1" : "data_1"},
{"data_2" : "data_2"},
...
]
I tried this:
$result = Get-ChildItem $Path2Search -recurse | Select-String -Pattern '(?<=locI(.*)\(\").+?(?=\")' -casesensitive | foreach {$_.matches} | select value | ConvertTo-Json | Out-File $save2file
But I'm getting this:
{
"Value": "data_1"
},
{
"Value": "data_2"
},
While I want it like this:
{
"data_1": "data_1"
},
{
"data_2": "data_2"
},
Any advice how? :)
Upvotes: 1
Views: 174
Reputation: 125332
You can first shape the result in a list of key-values then convert it to json.
For example if your input is a comma separated string, you can use:
$input = "data_1, data_2, data_3"
$input.Split(',').Trim() |
ForEach-Object {@{$_=$_}} |
ConvertTo-Json |
Out-File "C:\test.txt"
Or if the input is a string array:
$input = @("data_1", "data_2", "data_3")
$input | ForEach-Object {@{$_=$_}} |
ConvertTo-Json |
Out-File "C:\test.txt"
And the result would be:
[
{
"data_1": "data_1"
},
{
"data_2": "data_2"
},
{
"data_3": "data_3"
}
]
While I prefer to use above solution for creating json result, but you also can rely on string manipulation as well:
$input = "data_1, data_2, data_3"
@"
[
`t$(($input -split '\s*,\s*' |%{"{ `"$_`" : `"$_`" }"}) -join ",`n`t")
]
"@
Upvotes: 3