Search code examples
jsonkey-valueremap

Rename JSON key field with value in object


Have the following json output:

[
{
    "id": "47",
    "canUpdate": true,
    "canDelete": true,
    "canArchive": true,
    "info": [
        {
            "key": "problem_type",
            "value": "PAN",
            "valueCaption": "PAN",
            "keyCaption": "Category"
        },
        {
            "key": "status",
            "value": 3,
            "valueCaption": "Closed",
            "keyCaption": "Status"
        },
        {
            "key": "insert_time",
            "value": 1466446314000,
            "valueCaption": "2016-06-20 14:11:54.0",
            "keyCaption": "Request time"
        }

As you can see under "info" they actually label the key:value pair as "key": "problem_type" and "value": "PAN" and then "valueCaption": "PAN" "keyCaption": "Category". What I need to do is remap the file so that, in this example, it shows as "problem_type": "PAN" and "Category": "PAN". What would be the best method to iterate through the output to remap the key:value pairs in this manner?

How it needs to be:

[
{
    "id": "47",
    "canUpdate": true,
    "canDelete": true,
    "canArchive": true,
    "info": [
        {
            "problem_type": "PAN",
            "Category": "PAN"
        },
        {
            "status": 3,
            "Status": "Closed"
        },
        {
            "insert_time": 1466446314000,
            "Request time": "2016-06-20 14:11:54.0"
        }

Solution

  • Here is a jq solution which uses Update assignment |=

    .[].info[] |= {(.key):.value, (.keyCaption):.valueCaption}
    

    Sample Run (assumes data in data.json)

    $ jq -M '.[].info[] |= {(.key):.value, (.keyCaption):.valueCaption}' data.json
    [
      {
        "id": "47",
        "canUpdate": true,
        "canDelete": true,
        "canArchive": true,
        "info": [
          {
            "problem_type": "PAN",
            "Category": "PAN"
          },
          {
            "status": 3,
            "Status": "Closed"
          },
          {
            "insert_time": 1466446314000,
            "Request time": "2016-06-20 14:11:54.0"
          }
        ]
      }
    ]
    

    Try it online at jqplay.org