【问题标题】:Replace a character with another in object keys在对象键中用另一个字符替换一个字符
【发布时间】:2020-04-25 10:05:32
【问题描述】:

我正在学习如何使用 jq 来操作 json 数据, 我有点麻烦。 这是我的输入 JSON

{
   "user":{
      "advertisingID":"617a68"
   },
   "deviceTs":1575387020137,
   "activies":[
       {
         "ts":1575617868326,
         "appsUsage":{
            "isFull":true,
            "data":[
               {
                  "com.orange.phone":44009
               }
            ],
            "startTs":1575617281541
         }
      },
      {
         "ts":1575618968326,
         "appsUsage":{
            "isFull":true,
            "data":[
               {
                  "uk.green.launcher2":4354
               },
               {
                  "com.black.phone":1232
               }
            ],
            "startTs":1575617281541
         }
      }
   ]
}

我想用“破折号”替换所有包含“点”的键 和预期的输出:

{
   "user":{
      "advertisingID":"617a68"
   },
   "deviceTs":1575387020137,
   "activies":[
       {
         "ts":1575617868326,
         "appsUsage":{
            "isFull":true,
            "data":[
               {
                  "com-orange-phone":44009    <----
               }
            ],
            "startTs":1575617281541
         }
      },
      {
         "ts":1575618968326,
         "appsUsage":{
            "isFull":true,
            "data":[
               {
                  "uk-green-launcher2":4354   <----
               },
               {
                  "com-black-phone":1232      <----
               }
            ],
            "startTs":1575617281541
         }
      }
   ]
}

我试过了 .activies |= map( with_entries(if .key == "appsUsage" then ... else . end) ) ... (split(".")|join("-")) 但没有成功, 提前致谢。

【问题讨论】:

    标签: json key jq


    【解决方案1】:

    我认为您不需要正则表达式;我相信 split 和 join 内置函数的结合会更有效和更干净。

    .activies |= walk(
      if type == "object" then
        reduce (keys_unsorted[] | select(index("."))) as $k (.;
          (.[$k | split(".") | join("-")] = .[$k])
          | del(.[$k])
        )
      else . end
    )
    

    Online demo

    根据 peak 的建议,一个更易读的解决方案:

    .activies |= walk(
      if type == "object" then
        with_entries(
          .key |= gsub("\\.";"-")
        )
      else . end
    )
    

    Online demo

    【讨论】:

    • 太好了,请帮助返回完整的数据对象作为输入,我的意思是,它包括所有其他属性 ...user、deviceTs ....
    猜你喜欢
    • 2020-02-08
    • 2011-08-21
    • 2021-06-15
    • 2013-12-03
    • 2012-01-01
    • 2011-11-14
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    相关资源
    最近更新 更多