使用jq在JSON结构中更深入地转换键的名称 [英] Transforming the name of key deeper in the JSON structure with jq

查看:111
本文介绍了使用jq在JSON结构中更深入地转换键的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json:

{
  "vertices": [
    {
      "__cp": "foo",
      "__type": "metric",
      "__eid": "foobar",
      "name": "Undertow Metrics~Sessions Created",
      "_id": 45056,
      "_type": "vertex"
    },
    ...
  ]
  "edges": [
  ...

,我想实现这种格式:

{
  "nodes": [
    {
      "cp": "foo",
      "type": "metric",
      "label": "metric: Undertow Metrics~Sessions Created",
      "name": "Undertow Metrics~Sessions Created",
      "id": 45056
    },
    ...
  ]
  "edges": [
  ...

到目前为止,我已经能够创建此表达式:

So far I was able to create this expression:

jq '{nodes: .vertices} | del(.nodes[]."_type", .nodes[]."__eid")'

即将顶点"重命名为节点",并删除"_type"和"__eid",如何重命名嵌套在JSON中更深的键?

I.e. rename 'vertices' to 'nodes' and remove '_type' and '__eid', how can I rename a key nested deeper in the JSON?

推荐答案

如果使用with_entries(filter),则可以更改对象属性的名称.这会将一个对象转换为键/值对的数组,并对该对应用一个过滤器,然后转换回一个对象.因此,您只想将这些对象的键更新为您的新名称.

You can change the names of properties of objects if you use with_entries(filter). This converts an object to an array of key/value pairs and applies a filter to the pairs and converts back to an object. So you would just want to update the key of those objects to your new names.

根据所使用的jq版本,下一部分可能会很棘手.直到jq 1.5才引入字符串替换.如果可以的话,您可以执行以下操作:

Depending on which version of jq you're using, the next part can be tricky. String replacement doesn't get introduced until jq 1.5. If that was available, you could then do this:

{
    nodes: .vertices | map(with_entries(
        .key |= sub("^_+"; "")
    )),
    edges
}

否则,如果您使用的是jq 1.4,则必须手动将其删除.递归函数可以帮助解决这一问题,因为下划线的数量会有所不同.

Otherwise if you're using jq 1.4, then you'll have to remove them manually. A recursive function can help with that since the number of underscores varies.

def ltrimall(str): str as $str |
    if startswith($str)
        then ltrimstr($str) | ltrimall(str)
        else .
    end;
{
    nodes: .vertices | map(with_entries(
        .key |= ltrimall("_")
    )),
    edges
}

这篇关于使用jq在JSON结构中更深入地转换键的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆