【问题标题】:Parsing JSON file in powershell with specific characters在PowerShell中使用特定字符解析JSON文件
【发布时间】:2018-10-21 07:10:26
【问题描述】:

我正在尝试在特定字符内获取 powershell 中的值。基本上我有一个包含数千个这样的对象的 json

  "Name": "AllZones_APOPreface_GeographyMatch_FromBRE_ToSTR",
  "Sequence": 0,
  "Condition": "this.TripOriginLocationCode==\"BRE\"&&this.TripDestinationLocationCode==\"STR\"",
  "Action": "this.FeesRate=0.19m;this.ZoneCode=\"Zone1\";halt",
  "ElseAction": ""

我想要\"\"中的所有内容

IE 这里我会看到 BRE 和 STR 是 Zone1

我只需要输出这三样东西。

我一直在寻找如何使用 ConvertFrom-Json 来实现,但没有成功,也许我只是没有找到关于这方面的好文章。

谢谢

【问题讨论】:

    标签: json powershell parsing


    【解决方案1】:

    首先将您的 JSON 表示为字符串:

    $myjson = @'
    {
      "Name": "AllZones_APOPreface_GeographyMatch_FromBRE_ToSTR",
      "Sequence": 0,
      "Condition": "this.TripOriginLocationCode==\"BRE\"&&this.TripDestinationLocationCode==\"STR\"",
      "Action": "this.FeesRate=0.19m;this.ZoneCode=\"Zone1\";halt",
      "ElseAction": ""
    }
    '@
    

    接下来,创建一个匹配 \"\" 之间所有内容的正则表达式,长度小于 10 个字符(否则它将匹配不需要的结果)。

    $regex = [regex]::new('\\"(?<content>.{1,10})\\"')
    

    接下来,通过在正则表达式上调用Matches() 方法来执行正则表达式比较。将您的 JSON 字符串作为您要执行比较的文本传递到方法参数中。

    $matchlist = $regex.Matches($myjson)
    

    最后,获取在正则表达式中定义的content 匹配组,并从中提取值。

    $matchlist.Groups.Where({ $PSItem.Name -eq 'content' }).Value
    

    结果

    BRE
    STR
    Zone1
    

    方法 #2:使用 Regex Look-behinds 进行更准确的匹配

    这是一个更具体的正则表达式,它使用后视来适当地验证每个字段。然后我们将每个匹配项分配给开发人员友好的变量名称。

    $regex = [regex]::new('(?<=TripOriginLocationCode==\\")(?<OriginCode>\w+)|(?<=TripDestinationLocationCode==\\")(?<DestinationCode>\w+)|(?<=ZoneCode=\\")(?<ZoneCode>\w+)')
    $matchlist = $regex.Matches($myjson)
    
    ### Assign each component to its own friendly variable name
    $OriginCode, $DestinationCode, $ZoneCode = $matchlist[0].Value, $matchlist[1].Value, $matchlist[2].Value
    
    ### Construct a string from the individual components
    'Your origin code is {0}, your destination code is {1}, and your zone code is {2}' -f $OriginCode, $DestinationCode, $ZoneCode
    

    结果

    Your origin code is BRE, your destination code is STR, and your zone code is Zone1
    

    【讨论】:

    • 感谢您的帮助。我试试这个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2017-07-13
    相关资源
    最近更新 更多