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?

asked Nov 9, 2020 at 10:04

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
answered Nov 9, 2020 at 10:09
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.