Reputation: 185
I have here a set of json objects.
[
{
"group": "GroupName1",
"name": "Name1",
"nick": "Nick1",
"host": "Hostname1",
"user": "user1",
"sshport": "22",
"httpport": "80"
},
{
"group": "GroupName2",
"name": "Name2",
"nick": "Nick2",
"host": "hostname2",
"user": "user2",
"sshport": "22",
"httpport": "80"
}
]
I have a CLI script taking raw_input and building a new dict object containing the new object parameters as such:
def main():
# CLI Input
group_in = raw_input("Group: ")
name_in = raw_input("Name: ")
nick_in = raw_input("Nick: ")
host_in = raw_input("Host: ")
user_in = raw_input("User: ")
sshport_in = raw_input("SSH Port: ")
httpport_in = raw_input("HTTP Port: ")
# New server to add
jdict = {
"group": group_in,
"name": name_in,
"nick": nick_in,
"host": host_in,
"user": user_in,
"sshport": sshport_in,
"httpport": httpport_in
}
Assuming json file containing the aforementioned json objects formatted as such is loaded as:
with open(JSON_PATH, mode='r') as rf:
jf = json.load(rf)
I know how to do this by hacking the file using readlines/writelines, but how would I add jdict
in at the end of jf
pythonically so I can just write the file back with the complete new set of objects formatted in the same way?
Upvotes: 0
Views: 386
Reputation: 1122562
jf
is now just a Python list, so you can append the new dictionary to your list:
jf.append(jdict)
then write out the whole object back to your file, replacing the old JSON string:
with open(JSON_PATH, mode='w') as wf:
json.dump(jf, wf)
Upvotes: 2