Python passing variable with multiple lines to payload - python

Below is the part of code I am trying to execute.
msg="""line1
line 2"""
msg=f"\"{msg}\""
payload="{\"Additional comments\" :"+msg+",\n \"Short description\" : \"tests\",\n \"Requester\" : \"test1\",\n \"Impact\" : \"3\",\n \"Contact type\" : \"test1 \"\n\n}\n"
My code throws this error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
But when I send a message as:
#without a new line \n, my code works fine
msg="Line one" # code works fine

Put your data in a Python dictionary and use the json module to generate the text. It will write valid JSON much more easily that trying to format it manually:
import json
msg = '''line1
line2'''
data = {'Additional comments' : msg,
'Short description' : 'tests',
'Requester' : 'test1',
'Impact' : '3',
'Contact type' : 'test1'}
text = json.dumps(data,indent=2)
print(text)
Output:
{
"Additional comments": "line1\nline2",
"Short description": "tests",
"Requester": "test1",
"Impact": "3",
"Contact type": "test1"
}

Related

how can i retrieve value in JSON string in lambda python3

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?
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}"}'}]
I don't think you need to do any thing the output of boto3 client has always been in JSON string.

When I try to read a JSON data from a file (exported from xlsx) in python, it throws KeyError

I had .xlsx file, and I converted it to JSON. I am using python to get the data from this json file. I am able for example to search for Build# and then I get the corresponding level, but when I search for values in, for example, "14H0232" or "14H4812" it throws a KeyError.
'''
import json
f = open('try.json')
data = json.load(f)
input= input('Enter the value: ')
for i in data['F6']:
if i['14H0232'] == input:
print(i['LEVEL'])
f.close()
'''
A Snippet of the json file.
'''
{
"F6": [
{
"LEVEL": "2.0.6.0",
"ID": "dataID",
"Build#": "9",
"prod/dev": "prod ",
"14H4812": "data1\r\ndata2",
"14H4826": "data",
"14H4813": "data1\r\ndata2"
}
],
"F5": [
{
"LEVEL": "2.0.5.1",
"ID": "dataID",
"Build#": "18",
"prod/dev": "prod",
"14H0232": "data1: data1\r\ndata2: data2\r\ndata3: data3",
"14H12321": "data1\r\ndata2"
}
],
"F4": [
{
"LEVEL": "2.0.4.1",
"ID": "dataID",
"Build#": "18",
"prod/dev": "prod",
"14H0232": "data1: data1\r\ndata2: data2\r\ndata3: data3",
"14H12321": "data1\r\ndata2"
}
]
}
'''
The problem is in your loop. When you are trying to access the value for "14H0232" it just doesnt exist in your json file. The case for 'Build#' is different I assume, as the key is always there. The example you shared is also not showing that F6 has a key with that id you specified.
So to avoid this kind of errors you can put your 'if' statement in a try block and catch the error.
try:
if i['14H0232'] == input:
print(i['LEVEL'])
except KeyError:
print("The key is not found but the code continues to execute")

Error in code: python3 JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have a JSON file that I am trying to load to python but for whatever reason, yields the error, "python3 JSONDecodeError: Expecting value: line 1 column 1 (char 0)".
Here is my code:
def extract():
with open (file, 'r') as f:
data = json.load(f)
print (data)
The format of the JSON file is
{
"question" : {
"0cGufvFVCR" : {
"answer" : "___",
"date" : "___",
"email" : "___",
"que" : "___"
print(repr(f.read())) yields a string in the format '{\n "question" : {\n "0cGufvFVCR" : {\n "answer" : 100,\n "date" : "Mar 26, 2020",\n "

Parse json string in Python

A simple one, but I've just not yet been able to wrap my head around parsing nested lists and json structures in Python...
Here is the raw message I am trying to parse.
{
"Records": [
{
"messageId": "1b9c0952-3fe3-4ab4-a8ae-26bd5d3445f8",
"receiptHandle": "AQEBy40IsvNDy33dOhn4KB8+7apBecWpSuw5OgL9sw/Nf+tM2esLgqmWjGsd4n0oqB",
"body": "{\n \"Type\" : \"Notification\",\n \"MessageId\" : \"dce5c301-029f-55e1-8cee-959b1ad4e500\",\n \"TopicArn\" : \"arn:aws:sns:ap-southeast-2:062497424678:vid\",\n \"Message\" : \"ChiliChallenge.mp4\",\n \"Timestamp\" : \"2020-01-16T07:51:39.807Z\",\n \"SignatureVersion\" : \"1\",\n \"Signature\" : \"oloRF7SzS8ipWQFZieXDQ==\",\n \"SigningCertURL\" : \"https://sns.ap-southeast-2.amazonaws.com/SimpleNotificationService-a.pem\",\n \"UnsubscribeURL\" : \"https://sns.ap-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:062478:vid\"\n}",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1579161099897",
"SenderId": "AIDAIY4XD42",
"ApproximateFirstReceiveTimestamp": "1579161099945"
},
"messageAttributes": {},
"md5OfBody": "1f246d643af4ea232d6d4c91f",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:ap-southeast-2:062497424678:vid",
"awsRegion": "ap-southeast-2"
}
]
}
I am trying to extract the Message in the body section, ending up with a string as "ChiliChallenge.mp4\"
Thanks!
Essentially I just keep getting either TypeError: string indices must be integers or parsing the body but not getting any further into the list without an error.
Here's my attempt:
import json
with open ("event_testing.txt", "r") as myfile:
event=myfile.read().replace('\n', '')
str(event)
event = json.loads(event)
key = event['Records'][0]['body']
print(key)
you can use json.loads to load string
with open ("event_testing.txt", "r") as fp:
event = json.loads(fp.read())
key = json.loads(event['Records'][0]['body'])['Message']
print(key)
'ChiliChallenge.mp4'
Say your message is phrase,
I rebuild your code like:
phrase_2 = phrase["Records"]
print(phrase_2[0]["body"])
Then it works clearly. Because beginning of the Records, it looks like an array so you need to organized it.

How to construct xml element with attribute using python zeep?

I'm trying to contact SOAP api with xml defined as: http://www.etrzby.cz/assets/cs/prilohy/EETXMLSchema.xsd . I've used this question ( How to construct SOAP message with pysimplesoap? ) and created following code in python :
import zeep
import datetime
wsdl = 'http://www.etrzby.cz/assets/cs/prilohy/EETServiceSOAP.wsdl'
client = zeep.Client(wsdl=wsdl,transport=transport)
daco = client.service.OdeslaniTrzby(Hlavicka = {
'uuid_zpravy' : '1',
'dat_odesl' : datetime.datetime.now(),
'prvni_zaslani' : '1',
'overeni' : "true"
}, Data={
'dic_popl' : '',
#'dic_poverujiciho' : '',
'id_provoz' : '151151',
'id_pokl' : '102',
'porad_cis' : '1',
'dat_trzby' : datetime.datetime.now(),
'celk_trzba' : '100',
'rezim' : '0'
}, KontrolniKody = {
'pkp' : {'digest': 'SHA256', 'cipher' : 'RSA2048', 'encoding' : 'base64'},
'bkp' : {'digest': 'SHA1', 'encoding' : 'base16'}
})
My question is following, the part with "KontrolniKody" at the end contains pkp and bkp elements. Pkp should have attributes digest, cipher and encoding (not sure if I put that correctly inside) and it should also contain the ~340 chars of generated code but I'm not sure where or how to put that in the element.
Anyone got any ideas? Thanks for the help either way.

Categories