skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here is the code to achieve my desired output

    result = session.get(urljoin(baseurl, path), headers=headers, params=querystring, verify=False)
      ruletree = result.json()
      now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
      new_d = {"date_time": now, **ruletree}
      with open('/opt/bamboo/logs/outputfile', 'a') as outfile:
        json.dump(new_d, outfile)
        print(file=outfile)
    

  2. You’re calling it "jsonarray", but it is neither JSON nor is it an array. It is a simple Python dictionary.

        now = datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
        result = session.get(urljoin(baseurl, path), headers=headers, params=querystring, verify=False)
        jsonarray = result.json()
        jsonarray['date_time'] = now
        with open("/opt/bamboo-agents/akamai/logs/outputfile", "a") as outfile:
            json.dump( jsonarray, outfile )
    

    HOWEVER, be aware that the result file is not valid JSON. A JSON document is a single structure, not a set of separate structures.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search