【问题标题】:altering json value to be substring将 json 值更改为子字符串
【发布时间】:2019-06-07 12:04:59
【问题描述】:

我在 json 结果集中有一个值,我想将其更改为原始的子字符串值

{
   "label": "web page check",
  "target": "http://www.example.com/random/page"
},
{
   "label": "web page check1 ",
  "target": "http://www.example1.com/random/page"
}, 

我想做的是将它返回为

{
  "label": "web page check",
  "target": "https://www.example.com"
},
{
   "label": "web page check",
  "target": "https://www.example1.com"
}

我试过了

jq  '.[].target=(match(^https:\/\/[0-9a-zA-z.]*|^http:\/\/[0-9a-zA-z.]*).string)'

jq -c '.[] | {label: .label, target: (.target |=match(^https:\/\/[0-9a-zA-z.]*|^http:\/\/[0-9a-zA-z.]*).string})'

【问题讨论】:

  • 您似乎不打算更改“标签”值之一,并且显示的数据的 sn-p 旨在成为 JSON 数组的一部分。请修正和/或澄清。遵循minimal reproducible example 指南有助于避免此类问题。
  • 另外,问题的给定标题与示例暗示的要求相冲突,将“http:”更改为“https:”。请酌情修正标题或示例。

标签: json regex jq


【解决方案1】:

使用capture 通常比使用match 更容易。在您的情况下,假设您的输入是沿 sn-p 建议的行的对象数组,则以下内容足以修改“目标”值:

map(.target |= (capture("https?(?<s>://[^/]*)") | "https" + .s))

等价:

map(.target |= sub( "https?(?<s>://[^/]*).*"; "https" + .s) )

【讨论】:

    【解决方案2】:

    sub 的第一个参数(需要 jq 1.5)可以是任何 PCRE。

    .[].target |= sub("(?<=com).*$"; "")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2012-10-03
      • 2014-04-06
      • 2015-12-25
      • 1970-01-01
      相关资源
      最近更新 更多