Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jq how can I replace the name of a key with something else

Tags:

json

key

jq

This should be easy enough... I want to rename a few keys (ideally with jq), whatever I do seems to error though. Here is a json example below:

[  {   "fruit": "strawberry",   "veg": "apple",   "worker": "gardener"  } ] 

I'd like to rename the veg key to fruit2 (or example, whatever is easiest) and also the worker key to job.

I realize this is possible in sed, but I'm trying to get to grips with jq

like image 360
keeer Avatar asked Apr 20 '17 14:04

keeer


People also ask

How do I rename a key in JSON?

Syntax: obj['New key'] = obj['old key']; Note: Renaming the object by simple assignment of variable could be applied on multiple key, value pairs.


2 Answers

Use the following jq approach:

jq '[.[] | .["fruit2"] = .veg | .["job"] = .worker | del(.veg, .worker)]' file 

The output:

[   {     "fruit": "strawberry",     "fruit2": "apple",     "job": "gardener"   } ] 
like image 67
RomanPerekhrest Avatar answered Sep 17 '22 15:09

RomanPerekhrest


The key (:-) is with_entries. E.g., given a single object:

with_entries(if .key == "veg" then .key = "fruit2" else . end) 

In your case, since you have an array of objects, you could wrap the above in map( ... ).

like image 38
peak Avatar answered Sep 19 '22 15:09

peak