I need to add timestamp in key-value format on a JSON response. This is what I have right now:
now = datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
result = session.get(urljoin(baseurl, path), headers=headers, params=querystring, verify=False)
jsonarray = result.json()
json_object = json.dumps(jsonarray)
#writing to outputfile
with open("/opt/bamboo/logs/outputfile", "a") as outfile:
outfile.write(now + json_object + "n")
current output looks like this
2023-06-26 12:41:49{"account": "act_F-AC-1234", "contract": "ctr_F-1234"}
2023-06-26 12:42:49{"account": "act_F-AC-5678", "contract": "ctr_F-5678"}
my desired output should be
{"date_time": "2023-06-26 12:41:49", "account": "act_F-AC-1234", "contract": "ctr_F-1234"}
{"date_time": "2023-06-26 12:42:49", "account": "act_F-AC-5678", "contract": "ctr_F-5678"}
please note that the actual API call result (result.json) looks like below in proper format
{
"account": "act_F-AC-1234",
"contract": "ctr_F-1234",
"rules": {
"name": "default",
"children": [
{
"name": "Route to origin",
"children": [],
"behaviors": [
{
"name": "origin",
"options": {
"originType": "CUSTOMER",
"hostname": "elb.test.gateway.origin.com",
thanks in advance
2
Answers
Here is the code to achieve my desired output
You’re calling it "jsonarray", but it is neither JSON nor is it an array. It is a simple Python dictionary.
HOWEVER, be aware that the result file is not valid JSON. A JSON document is a single structure, not a set of separate structures.