Home > Net >  how can i retrieve value in JSON string in lambda python3
how can i retrieve value in JSON string in lambda python3

Time:07-06

I'm developing an AWS lambda function that is triggered from an event bridge and then putting another event using python but struggling to retrieve a value from a variable in the Json string

below is the code

import json, boto3

client = boto3.client('events')

def lambda_handler(event, context):

testV2_dict={  
 "K1" : event['e1'] ,
"K2" : event['e2'] 
}

#converting python to json as (put_event - Details) section is expecting json
testV2=json.dumps(testV2_dict)

response = client.put_events(
         Entries=
          [
            {
             "DetailType": "test",
             "Source": "test",
             "Detail": "{ \"testK\": \"testV\",\"testK2\": \""  testV2  "\" }"
           }
          ]
        )

tried to add Details on different ways, "Detail": "{ \"testK\": \"testV\",\"testK2\": \"" testV2 "\" }" and still getting error as Malformated Details and if i deleted the , I'm getting word testV2 itself not the value from the above

How can I retrieve the value of testV2 in the Details inside the event?

CodePudding user response:

You don't have enough escaping in there. If testV2 is supposed to be a JSON string emebedded in a JSON string embedded in as JSON string, then you need more string escapes. I would let json.dumps handle that:

import json
event = {'e1': 99, 'e2': 101}

testV2_dict={  
 "K1" : event['e1'] ,
 "K2" : event['e2'] 
}

testV2=json.dumps(testV2_dict)

detail = {
    "testK": "testV",
    "testK2": testV2
}

Entries= [
    {
     "DetailType": "test",
     "Source": "test",
     "Detail": json.dumps(detail),
   }
]

print(Entries)

Output:

[{'DetailType': 'test', 'Source': 'test', 'Detail': '{"testK": "testV", "testK2": "{\\"K1\\": 99, \\"K2\\": 101}"}'}]

CodePudding user response:

I don't think you need to do any thing the output of boto3 client has always been in JSON string.

  • Related