Search code examples
jsonpowershellkeykey-value-store

Convert list of values to a key value json


I'm trying to convert a list comma separated IP values (192.168.1.1,192.168.1.2,192.168.1.3, xxxx,xxxx) to a key value json so that at the end of all I can have a file with the structure below.

 {
    "ips": [
        {
            "ip": "192.168.1.1"
        },
        {
            "ip": "192.*.*.*"
        },
        {
            "ip": "192.168.1.3/32"
        }
    ]
}

I was trying to user the command ConvertTo-Json command form powershell but really don't manage how to get it.

Home anyone can give me a hand and guide me how to handle this issue

Thanks you very much


Solution

  • Create objects or hashtables with the same contents and structure as your desired JSON, then pipe to ConvertTo-Json:

    @{
        'ips' = @(
            @{ "ip" = "192.168.1.1" },
            @{ "ip" = "192.*.*.*" },
            @{ "ip" = "192.168.1.3/32" },
        )
    } |ConvertTo-Json |Set-Content path\to\output.json
    

    Now you just need to generate the inner hashtables from a list instead of hardcoding them:

    $listOfIPs = '192.168.1.1,192.*.*.*,192.168.1.3/32' -split ','
    
    @{
        'ips' = @(
            $listOfIPs |ForEach-Object { @{ "ip" = $_ } }
        )
    } |ConvertTo-Json |Set-Content path\to\output.json