Home > database >  I am unable to call the json from the json file
I am unable to call the json from the json file

Time:06-25

This is my json file json1.json

[

{"host" : "192.168.0.25", "username":"server2", "path":"/home/server/.ssh/01_id"},
{"host" : "192.168.0.26", "username":"server3", "path":"/home/server/.ssh/01_id"},
{"remotes": ["/home/server2/Desktop/backupdestination/", "/home/server3/Desktop/backupdestination/"]}
]

I am unable to call the remotes from the json file in my python script , i tried doing this but got error

json_file = open('/path/to/file') 
destinations = json.load(json_file)
remotes = destinations['remotes']
json_file.close()
for destination in remotes:
    destination  = f'/{year}/{month}/{date}'

CodePudding user response:

You need to add something like this:

for dicts in destinations:
    if 'remotes' in dicts:
        remotes = dicts['remotes']

before your final loop to locate the dictionary with 'remotes' key in the array of dictionaries.

CodePudding user response:

json_file = open('/path/to/file') 
destinations = json.load(json_file)
remotes = destinations['remotes']
json_file.close()
for destination in remotes:
    destination  = f'/{year}/{month}/{date}'

There are quite a few things wrong here.

  1. You should start using context managers (with statement) which handles file closing even in the case of an Exception!

  2. You are trying to add on to your element in your iteration.

    for destination in remotes:
        destination  = xyz 
    

Destination is a variable which is newly created each next, thus any changes made to it will be overwritten.

  1. Where do you get your year/month/date from? It’s unclear in this example.
  2. What error does Python throw?
  3. What are you trying to do in general?
  • Related