Replace String in a JSON file

Viewed 1347
"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 a part of the json file. I need to edit the hosts part with two different IPs using a script. Anyone have any idea

2 Answers

For proper json (your data above surrounded by {}) using jq:

$ 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"
  }
}

You can use Json python package

import json

my_bytes_value = response.content
my_json = my_bytes_value.decode('utf8')
jsonResponse = json.loads(my_json)
resultCount = jsonResponse["cassandra"]
Related