Python – Replaces strings in JSON files

Replaces strings in JSON files… here is a solution to the problem.

Replaces strings in JSON files

"cassandra": {
    "host": "1.1.1.1",
    "portNo": "9042",
    "keyspace": "good"
},
"postgres": {
    "host": "2.2.2.2",
    "portNo": "5432",
    "database": "dude",
    "username": "root",
    "password": "something"
}

This is part of the JSON file. I need to use a script to edit the part of the host with two different IPs. Anyone has any ideas

Solution

Use jq to get the correct JSON (the data above is surrounded by {}):

$ jq '.|. cassandra.host="foo"' file.json
{
  "cassandra": {
    "host": "foo",
    "portNo": "9042",
    "keyspace": "good"
  },
  "postgres": {
    "host": "2.2.2.2",
    "portNo": "5432",
    "database": "dude",
    "username": "root",
    "password": "something"
  }
}

Related Problems and Solutions