且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jq在JSON结构中更深入地转换键的名称

更新时间:2023-12-02 10:47:16

如果使用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
}