Transforming the name of key deeper in the JSON structure with jq

后端 未结 3 1395
野性不改
野性不改 2021-01-16 09:46

I have following json:

{
  \"vertices\": [
    {
      \"__cp\": \"foo\",
      \"__type\": \"metric\",
      \"__eid\": \"foobar\",
      \"name\": \"Undert         


        
3条回答
  •  渐次进展
    2021-01-16 10:28

    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.

    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
    }
    

    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
    }
    

提交回复
热议问题