Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a field to a JSON object with the jq command?

Tags:

json

jq

I have this JSON data:

{
    "success": true,
    "module": {
        "data": {
            "item_i77f664a2": {
                "id": "i77f664a2",
                "tag": "item",
                "fields": {
                    "cartItemId": 2012636322
                },
                "type": "biz"
            }
        }
    }
}

And I want to add {"operation":"delete"} right below cartItemId and then save the JSON data to a file. The result that I want is like this:

{
    "success": true,
    "module": {
        "data": {
            "item_i77f664a2": {
                "id": "i77f664a2",
                "tag": "item",
                "fields": {
                    "cartItemId": 2012636322,
                    "operation": "delete"
                },
                "type": "biz"
            }
        }
    }
}

This is what I have tried:

jq '.module.data.item_i77f664a2.fields + {"operation":"delete"}' > data.json

But it doesn't save the JSON data with the output that I want like above. How do I fix it ?

like image 731
Joe Avatar asked Apr 03 '18 14:04

Joe


2 Answers

This type of update is where the magic of += comes into play. With your input, the following invocation:

jq '.module.data.item_i77f664a2.fields += {"operation":"delete"}'

produces the output you indicate you want:

{
  "success": true,
  "module": {
    "data": {
      "item_i77f664a2": {
        "id": "i77f664a2",
        "tag": "item",
        "fields": {
          "cartItemId": 2012636322,
          "operation": "delete"
        },
        "type": "biz"
      }
    }
  }
}

However, I am not sure that this will produce what you want in similar circumstances, as you have referenced "item_i77f61ee2".

like image 155
peak Avatar answered Sep 20 '22 14:09

peak


Thanks to @peak for his answer!

Just want to add,

Creating a blank json file:

echo "{}" > config.json

File Content:

{}

Then add properties to the file:

echo "$(jq '. += {"url": "https://url.com"}' config.json)" > config.json

File Content:

{
    "url": "https://url.com"
}

One more property:

echo "$(jq '. += {"name": "a Name"}' config.json)" > config.json

File Content:

{
    "url": "https://url.com",
    "name": "a Name"
}

If you have variables set and want to use that value (ie. Azure Build Pipelines) you can pass in that value as an argument (urlarg in this case):

URL="https://url.com"
echo "$(jq --arg urlarg "$URL" '. += {"url": $urlarg}' config.json)" > config.json
like image 23
Pierre Avatar answered Sep 21 '22 14:09

Pierre