PowerShell : retrieve JSON object by field value

前端 未结 6 2163
说谎
说谎 2020-12-07 15:15

Consider JSON in this format :

\"Stuffs\": [
    {
        \"Name\": \"Darts\",
        \"Type\": \"Fun Stuff\"
    },
    {
        \"Name\": \"Clean Toilet         


        
6条回答
  •  隐瞒了意图╮
    2020-12-07 15:59

    In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...

    Operating off the assumption that we have a file named jsonConfigFile.json with the following content from your post:

    {
        "Stuffs": [
            {
                "Name": "Darts",
                "Type": "Fun Stuff"
            },
            {
                "Name": "Clean Toilet",
                "Type": "Boring Stuff"
            }
        ]
    }
    

    This will create an ordered hashtable from a JSON file to help make retrieval easier:

    $json = [ordered]@{}
    
    (Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
        ForEach-Object { $json[$_.Name] = $_.Value }
    

    $json.Stuffs will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type key's value associated with the Clean Toilet key, you would retrieve it like this:

    $json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
    

    It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.

提交回复
热议问题