I have an output JSON file from an API call "ruletree" and I need to iterate through it to get values for domainName, rule & host keys. My ultimate goal is to put the iteration result into a new dictionary "newjson" and print in a log file called "domains".
current code
ruletree = result.json()
#code to get domainName, name & host
newjson =
#add date for every log line
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
new_d = {"date_time": now, **newjson}
#save to log file
with open('/opt/logs/domains', 'a') as outfile:
json.dump(new_d, outfile)
print(file=outfile)
ruletree content
ruletree = {
"contract": "1234",
"domainName": "www.domainA.com",
"rules": {
"name": "default",
"children": [
{
"rule": "Rule1",
"children": [],
"behaviors": [
{
"name": "origin",
"options": {
"originType": "CUSTOMER",
"host": "gateway1.com",
},
}
],
},
{
"rule": "Rule2",
"children": [],
"behaviors": [
{
"name": "origin",
"options": {
"originType": "CUSTOMER",
"host": "gateway2.com",
},
}
],
},
],
},
}
expected output
{"date_time": "2023-07-06 06:67:06", "domainName": "www.domainA.com", "rule": "Rule1", "host": "gateway1.com")
{"date_time": "2023-07-06 06:67:06", "domainName": "www.domainA.com", "rule": "Rule2", "host": "gateway2.com")
{"date_time": "2023-07-06 06:67:06", "domainName": "www.domainB.com", "rule": "Rule1", "host": "gateway1.com")
{"date_time": "2023-07-06 06:67:06", "domainName": "www.domainB.com", "rule": "Rule2", "host": "gateway2.com")
thanks in advance!
2
Answers
A simple generator function will do here.
Here’s the updated code with minimal changes, and it also fixes the issue while writing the JSONL file. The code in question would append a list of JSON to the file, which will make the file messier and hard to read through code.
File output: