1

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? :)

1 Answer 1

3

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")
]
"@
Sign up to request clarification or add additional context in comments.

16 Comments

thanks, but in my case they are not comma separated, exactly data feeding from this line of code: $result = Get-ChildItem $Path2Search -recurse | Select-String -Pattern '(?<=locI(.*)\(\").+?(?=\")' -casesensitive | foreach {$_.matches} | select value any advice how to split it then?
Just put the array instead of $input.Split(',').Trim()
just put instead of not work, drop error: ConvertTo-Json : The type 'System.Collections.Hashtable' is not supported for serialization or deserialization of a dictionary. Keys must be strings
I make it work like this: ...foreach {$_.matches} | ForEach-Object -begin {$result = "{"} -process {$result = $result+$_.Value+":"+$_.Value+","} -end {$result = $result+"}"} $result | Out-File $output but that dont look like nice :/
How is it related to the code which I shared with you?!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.