首页 > 解决方案 > 如何拆分json中的字符串值并使用jq转换为嵌套对象?

问题描述

我正在尝试使用 jq 来转换如下内容:

[
  {
    "type": "Feature",
    "properties": {
      "osm_id": "172544",
      "highway": "crossing",
      "other_tags": "\"crossing\"=>\"uncontrolled\",\"tactile_paving\"=>\"yes\""
    },
    "geometry": {
      "type": "Point",
      "coordinates": [
        13.3432342,
        52.5666157
      ]
    }
  }
]

进入这个:

[
  {
    "type": "Feature",
    "properties": {
      "osm_id": "172544",
      "highway": "crossing",
      "other_tags": {
        "crossing": "uncontrolled",
        "tactile_paving": "yes"
      }
    },
    "geometry": {
      "type": "Point",
      "coordinates": [
        13.3432342,
        52.5666157
      ]
    }
  }
]

现在,这是我的进步:

jq 'map(try(.properties.other_tags |= split(",") // .)) | map(try(.properties.other_tags[] |= split("=>") // .)) | map(try(.properties.other_tags[] |= { (.[0]) : .[1] } // .))' example.json

但“other_tags”的输出如下所示:

  "other_tags": [
    {
      "\"crossing\"": "\"uncontrolled\""
    },
    {
      "\"tactile_paving\"": "\"yes\""
    }
  ]

我很确定这并没有达到预期的效果。

它用于转换相当大的 osm 导出

有没有更优雅/更短的 jq 指令我可以使用,也给我如上所述的所需输出?

标签: jsonopenstreetmapgeojsonjq

解决方案


你也可以使用这个:

<file jq '[.[] | try(.properties.other_tags |= ("{" + gsub("=>"; ":") + "}" | fromjson))//.]'

这将大括号{和添加}到想要的字符串并替换=>:. 然后使用命令将该字符串转换为 JSON 对象fromjson

.properties.other_tags如果未找到,该命令不会更改 JSON 数据。


推荐阅读