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

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

I have following json:

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


        
3条回答
  •  醉酒成梦
    2021-01-16 10:38

    The following program works with jq 1.4 or jq 1.5. It uses walk/1 to remove leading underscores from any key, no matter where it occurs in the input JSON.

    The version of ltrim provided here uses recurse/1 for efficiency and portability, but any suitable substitute may be used.

    def ltrim(c):
      reduce recurse( if .[0:1] == c then .[1:] else null end) as $x 
        (null; $x);
    
    # Apply f to composite entities recursively, and to atoms
    def walk(f):
     . as $in
     | if type == "object" then
          reduce keys[] as $key
            ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
      elif type == "array" then map( walk(f) ) | f
      else f
      end;
    
    .vertices = .nodes
    | del(.nodes)
    | (.vertices |= walk(
          if type == "object"
          then with_entries( .key |= ltrim("_") )
          else .
          end ))
    

提交回复
热议问题