使用 jq 下降 JSON 文档路径并更新字段名称

Descend JSON doc paths and update field names with jq

我想深入研究 MongoDB JSON 文档中的所有路径,并可能使用 jq 修改每个字段名称(mongo shell似乎无法做到这一点。)。具体来说,我想删除除“_id”之外的所有字段名称中的所有下划线(“_”)。我尝试了 recursewith_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"

最简单的是使用walk:

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

如果你的jq没有walk,你可以通过google轻松找到它的定义: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 ;