【问题标题】:Descend JSON doc paths and update field names with jq使用 jq 下降 JSON 文档路径并更新字段名称
【发布时间】:2018-12-13 20:19:53
【问题描述】:

我想深入了解 MongoDB JSON 文档中的所有路径,并可能使用 jq 修改每个字段名称(mongo shell 似乎无法做到这一点。)。具体来说,我想删除除“_id”之外的所有字段名称中的所有下划线(“_”)。我尝试了recurse 和with_entries 的各种组合,但没有成功。所以,例如,转换这个:

{
  "_id": "doc1",
  "field_11": "value_11",
  "field_12": {
    "field_121": {
      "field_1211": "value_1211",
      "field_1212": "value_1212"
    },
    "field_122": {
      "field_1221": "value_1221",
      "field_1222": "value_1222"
    }
  },
  "field_13": [
    {
      "field_131": {
        "field_1311": "value_1311",
        "field_1312": "value_1312"
      },
      "field_132": {
        "field_1321": "value_1321",
        "field_1322": "value_1322"
      }
    }
  ],
  "field_one_four": "value_one_four",
  "Field_One_Five": "Value_One_Five"
}

到这里:

{
  "_id": "doc1",
  "field11": "value_11",
  "field12": {
    "field121": {
      "field1211": "value_1211",
      "field1212": "value_1212"
    },
    "field122": {
      "field1221": "value_1221",
      "field1222": "value_1222"
    }
  },
  "field13": [
    {
      "field131": {
        "field1311": "value_1311",
        "field1312": "value_1312"
      },
      "field132": {
        "field1321": "value_1321",
        "field1322": "value_1322"
      }
    }
  ],
  "fieldonefour": "value_one_four",
  "FieldOneFive": "Value_One_Five"
}

奖励:如果我想删除下划线和将复合字段名称转换为驼峰式怎么办?即,"field_one_four" 将变为 "fieldOneFour","Field_One_Five" 将变为 "fieldOneFive"。

【问题讨论】:

    标签: key edit jq recursive-descent


    【解决方案1】:

    最简单的就是使用walk:

    walk( if type == "object"
          then with_entries( if .key != "_id" then .key |= gsub("_";"") else . end ) 
          else . end)
    

    如果你的 jq 没有 walk,你可以通过谷歌搜索轻松找到它的 def:jq "def walk"

    奖金

    您可以使用以下辅助函数:

    def camelcase:
      def u:  if 97 <= . and . <= 122 then . - 32  else . end;
      def c:
        if length <= 1 then
          if .[0] == 95 then [] else . end
        else if .[0] == 95 then [.[1]|u] + (.[2:] | c) else [.[0]] + (.[1:]|c) end
        end;
    
      explode | c | implode;
    

    额外奖励

    def camel_Case:
      if test("_")
      then .[0:1] as $first
      | if $first | (. ==  ascii_downcase)
        then $first | ascii_upcase + ([2:]|camelcase)
        else camelcase
        end
      else .
      end ;
    

    【讨论】:

    • 太棒了!您能否进行编辑以将"Field_One_Five" 转换为"fieldOneFive"?
    • 仅供参考,walk source code.
    猜你喜欢
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2019-08-25
    • 2023-01-24
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多