jsphdnl jsphdnl - 1 year ago 133
JSON Question

Using sed/awk to modify huge JSON file

I have a JSON file like this, i want to use sed/awk to replace certain keys and add new keys like, I cannot use json parsers like jq as this requires installation procedure and the product environment is limited.

Input:

[{
"key1": "value1",
"key2": "23456734",
"nestedKey1": {
"234567890": {
"key2": "value3",
"key4": "value4"
}
}
}]


Output:

[{
"key2": "value1:23456734",
"nestedKey1": {
"CONSTANT:234567890": {
"key4": "value4"
}
}
}]

Answer Source

sed is not the right tool for that.

That said, the following command will work with your sample file (use it at your own risk in your production environment) :

sed '
/ *"key1"/ {
  N
  s/ *"key1": "\([^"]*\)",\n\( *"key2": \)"\([0-9]*\)"/\2"\1:\3"/
}
/"nestedKey1": {/ {
  N
  s/"\([0-9]*"\)/ "CONSTANT:\1/
  n
  /key2/d
}
' file