1

I'm new in using jq library, Here i'm reading HotelInfo field of my json:

./jq-linux64 '.HotelInfo' 74687.json

{
  "HotelURL": "http://www.tripadvisor.com/aaa.html",
  "HotelID": "74687",
  "Price": "$156"
}

Now, i'm going to add {city: tehran} object to this array :

./jq-linux64 --arg city tehran '.HotelInfo +{city: $city}' 74687.json 

{
  "HotelURL": "http://www.tripadvisor.com/aaa.html",
  "HotelID": "74687",
  "Price": "$156",
  "city": "tehran"
}

And it's done, but this doesn't reflect on file too and file still not updated with this new record, How can i update the json file as well?

Sajad
  • 2,273
  • 11
  • 49
  • 92

3 Answers3

1

If you want to keep your original json structure and just append the new value you could use:

$ jq '.HotelInfo.city = "tehran"' 74687.json > 74687.jso.tmp
$ mv 74687.json.tmp 74687.json

This will update the file with all previous fields/objects if any:

{
  "HotelInfo": {
    "HotelURL": "http://www.tripadvisor.com/aaa.html",
    "HotelID": "74687",
    "Price": "$156",
    "city": "tehran"
  }
}

If you just want to create a new structure removing other possible keys within .HotelInfo

$ jq --arg city tehran '.HotelInfo +{city: $city}' 74687.json > 74687.jso.tmp 
$ mv 74687.json.tmp 74687.json

This will create the file with the Hotelinfo object contents only:

{
  "HotelURL": "http://www.tripadvisor.com/aaa.html",
  "HotelID": "74687",
  "Price": "$156",
  "city": "tehran"
}
nbari
  • 25,603
  • 10
  • 76
  • 131
  • why do you post this? I answered this already (30 min before your answer) – hek2mgl Jul 16 '18 at 14:45
  • 1
    @hek2mgl your answer will create a new json within the scope of the child object and therefore lose all the parent objects, something probably OP would not like. – nbari Jul 16 '18 at 14:50
  • I still don't see the difference. Anyhow probably I'm missing something here – hek2mgl Jul 16 '18 at 15:49
0

You need to write the results to a temporary file and rename that to the original one:

./jq-linux64 --arg city tehran '.HotelInfo +{city: $city}' 74687.json > temp.json
mv temp.json 74687.json
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

You could use sponge or write to a temporary file, and then "mv" it.

For further details and alternatives, see the following Q in the jq FAQ:

: How can "in-place" editing of a JSON file be accomplished? What is jq's equivalent of sed -i?

peak
  • 105,803
  • 17
  • 152
  • 177
  • Hihi, nice to meet here again after our discussion on github yesterday :) (I'm metashock on github). Note that while sponge is nice, it is very likely not installed on a server system – hek2mgl Jul 16 '18 at 14:41