0

I have this JSON file:

[
{
    "db_name":1,
    "daily" : {
               "days_to_backup" : [1,3,29],
               "delete_after" : 14,              
             }
},
{
    "db_name":2,
    "daily" : {
               "days_to_backup" : [1,3,29],
               "delete_after" : 14,
              }

}
]

I have an input from user for the requested db_name and then for this specific db_name I want to loop through the array "days_to_backup". my code right now:

import argparse
import json
import sys
parser = argparse.ArgumentParser()

#-db DATABSE -t TYPE  -p PROCESSS
parser.add_argument("-p", "--process", help="Process")
parser.add_argument("-db", "--database", help="Database name")
parser.add_argument("-t", "--type", help="Backup type")



args = parser.parse_args()

print( "Process:{} Database:{} Type:{}   ".format(
        args.process,
        args.database,
        args.type,


        ))


with open('C:/Users/llll/Desktop/f.json') as f:
  data = json.load(f)


if  args.process == 'backup':
        print("Asked for backup")
        for keyval in data:
          if args.database == keyval['db_name']:
                print(args.database)
                print("Database exist")
                ## checked if the DB inserted exists, now i want here to loop through the array days_to_backup
                sys.exit()

        print("Database doesn't exist")

else:
        print("Currently support only backups")

How do I specify to loop through specific object of the JSON file?

1 Answer 1

1

Try the below

db_lst = [
    {
        "db_name": 1,
        "daily": {
            "days_to_backup": [1, 3, 29],
            "delete_after": 14,
        }
    },
    {
        "db_name": 2,
        "daily": {
            "days_to_backup": [1, 3, 29],
            "delete_after": 14,
        }

    }
]
db_name = 1
for entry in db_lst:
    if entry.get("db_name") == db_name:
        for day in entry["daily"]["days_to_backup"]:
            print(day)

output

1
3
29
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.