skip to Main Content

I have JSON data files that I’d like to modify somewhat. From:

{
    "alpha": "...",
    "beta": [ ... ],
    "delta": { ... },
    "gamma": "..."
}

to:

{
    "alpha": "...",
    "epsilon" : {
        "beta": [ ... ],
        "delta": { ... }
    },
    "gamma": "..."
}

This is, I want to define a subset of fields that I want to extract and move into a new object with a specific name. How do I perform such a task with jq?

2

Answers


  1. jq '{ alpha, epsilon: { beta, delta }, gamma }' input.json > output.json

    Login or Signup to reply.
  2. define a subset of fields that I want to extract and move

    Here’s a programmatic way:

    jq --argjson fields '["beta", "delta"]' '
     def project($fields): . as $in | reduce $fields[] as $k ({}; .[$k] = $in[$k]);
    
     .epsilon = project($fields)
     | delpaths( [$fields[]| [.]] )
     '
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search