首页 > 解决方案 > 使用 PowerShell 从 JSON 文件中获取某些值

问题描述

在过去的几个小时里,我看到了很多关于 JSON 和 PowerShell 的问题,但没有一个能帮助我找到解决这个特定问题的方法。我相信这很容易。

我想提取这个 JSON 对象中对象的所有url字段(原始 URL 是这样的: https://updates.jenkins.io/update-center.json):plugins

{
    "connectionCheckUrl": "http://www.google.com/",
    "core": {
        ...
    },
    "deprecations": {
        ...
    },
    "generationTimestamp": "2021-05-19T12:16:52Z",
    "id": "default",
    "plugins": {
        "42crunch-security-audit": {
            "buildDate": "Oct 06, 2020",
            "defaultBranch": "master",
            "dependencies": [
                ...
            ],
            "developers": [
                ...
            ],
            "excerpt": "Performs API contract security audit to get a detailed analysis of the possible vulnerabilities and other issues in the API contract.",
            "gav": "io.jenkins.plugins:42crunch-security-audit:3.8",
            "issueTrackers": [
                ...
            ],
            "labels": [
                ...
            ],
            ...
            "title": "42Crunch REST API Static Security Testing",
            "url": "http://archives.jenkins-ci.org/plugins/42crunch-security-audit/3.8/42crunch-security-audit.hpi",
        },
        "AnchorChain": {
            ...
            "url": "http://archives.jenkins-ci.org/plugins/AnchorChain/1.0/AnchorChain.hpi",
            ...
        },
        ... many hundreds more ...
    }
    ...
}

plugins对象每个插件包含一个对象,其中插件的名称是对象的键。所以我必须以某种方式遍历所有插件对象并寻找url属性。

我想/必须使用 PowerShell (v5.1) 执行此操作,但找不到简单的方法。这是我卡住的地方:

$all = (Get-Content(".\update-center.json") | convertfrom-json)
$all.gettype().fullname

$plugins = $all.plugins
$plugins.gettype().fullname

我得到这个结果:

System.Management.Automation.PSCustomObject
System.Management.Automation.PSCustomObject

现在我希望遍历各个plugin对象并简单地获取url密钥的属性,但我被困住了:

$plugins | get-member -MemberType NoteProperty | foreach name | foreach $plugins.$_.url

应该得到我想的get-member单个插件,但是数小时的 PowerShell 文档仔细研究显然已经让我的大脑发火了。帮助!:-)

标签: jsonpowershell

解决方案


像你一样导入你的 JSON$all

然后,用于$all.plugins | gm -MemberType Properties | select -expandproperty Name | %{ $all.plugins.$_.url}获取您的网址列表


推荐阅读