【问题标题】:Cannot get the urls filtered from JSON response using PowerShell无法使用 PowerShell 从 JSON 响应中过滤出 url
【发布时间】:2018-01-21 03:13:48
【问题描述】:

我的文件中有 JSON 原始内容。我正在尝试使用 ConvertFrom-Json 解析网址。不知何故,它不起作用。非常感谢您的想法。

$file1 = "C:\Test\output1.txt"
$file2 = "C:\Test\output2.txt"

$content = Get-Content $file1
$response = ConvertFrom-Json $content
$urls = $response.input | where {$_.url}
$urls | Out-File $file2

output1 文件中的原始内容为:

{"workitems":[{"Inputs":{"url":"http://www.cmha.ca/news-and-events/news/?70301308070201301010","c":"1"},"Outputs":{"ip":"50.56.166.145","latencymilliseconds":"785","httpstatuscode":"200","completeresponse":"HTTP/1.1 200 OK\r\nVary: ......etc}}]}

文件大小约为 10K KB。我们如何才能最好地解析并将 URL 获取到 output2.txt 文件?

【问题讨论】:

    标签: json powershell parsing


    【解决方案1】:

    运行以下代码

    $file1 = "file1.txt"
    $content = Get-Content $file1
    $response = ConvertFrom-JSON $content
    $urls = $response.workitems.inputs | where {$_.url}
    $urls.url
    

    输出

    http://www.cmha.ca/news-and-events/news/?70301308070201301010

    【讨论】:

    • 我的错,这是复制粘贴错误,但我使用了“输入”但系统抛出错误:无法将“System.Object []”转换为参数“所需的类型”“System.String”输入对象'。
    • @SunRays 将-Raw 添加到Get-Content
    • 非常感谢 Get-Content 的 -Raw 运行良好。我还在 JSON 响应之前和之后添加了方括号,因为 ConvertFrom-JSON 不喜欢不包含左方括号和右方括号 [] 的 JSON,而我的输出不包含 []。谢谢大家的帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-01-25
    • 2019-05-25
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多