ImranRazaKhan
ImranRazaKhan

Reputation: 2297

add array element from file into json array of other file with jq

I want to add an array element into an existing json file using jq.

element.json

{
  "category": "fiction",
  "author": "Evelyn Waugh",
  "title": "Sword of Honour",
  "price": 12.99
}

original.json

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

I tried following

jq ".store.book += [input] "  original.json  element.json

Above works fine and it added array and show output like below

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

Now two questions

then i used but sponge is not installed and i cant install it on production

jq ".store.book += [input] "  original.json  element.json | sponge original.json

Following is working for First

jq ".store.book += [input] "  original.json  element.json > original.tmp && mv original.tmp original.json

EDIT1: As per feedback i tried below but for second still error

jq ".store.book += [input.price=2] "  original.json  element.json

It throws error

jq: error (at element.json:6): Invalid path expression near attempt to access element "price" of {"category":"fiction","aut...

Upvotes: 0

Views: 187

Answers (1)

peak
peak

Reputation: 116730

First

[ input|.price |= $newprice ]

Second

The simplest would be to write the output to a temporary file, and then, perhaps after checking for success, moving it into place.

Upvotes: 1

Related Questions