Pyodbc + MSSQL 2017 generates JSON response to python app - json

My python app calls MSSQL 2017 function trough pyodbc and function query response is JSON formatted on the server side.
cursor.execute("SELECT dbo.fnInvoiceJSON(%s,%s);" % (posted,vat))
row = cursor.fetchone()
Response that returns in the app is a class 'pyodbc.Row like it should be.
I can pass this response trough requests.post to other API call if i convert this to to string.
Is there any way to convert this response a accessible python dict / JSON object?

As noted in the question, under pyodbc fetchone() returns a pyodbc.Row object and fetchall() returns an array of pyodbc.Row objects.
However, pyodbc also supports a fetchval() method that will return the value in the first column of the first row in the result set (similar to the ExecuteScalar method in C#). fetchval() returns the value as the corresponding Python type (e.g., string, None, etc.).

Related

Set dynamically created Java String to Json Values to perform Karate Integration Testing as a dynamically

I need to set the randomString/randomNumber to a Json Values. Current to complete my Karate Integration testing, I am passing hardcoded values as payload, But need to set the randomString/randomNumber as value for Json. I am having PUT HTTP verb.
I need to store the JSON values in DB as well.
Do you need just generate random value(number or string) and write it to you JSON, i right understand?
write some java code to generate random String/content and use in karate feature as below:
def emailID = common.getRandomString(7)+'#test.mail'
When def payload = <someData>
And set payload $.email = emailID
And request payload
Hope this solve your problem

Extracting JSON object from BigQuery Client in AWS Lambda using Python

I am running a SQL query via the google.cloud.bigquery.Client.query package in AWS lambda (Python 2.7 runtime). The native BQ object extracted from a query is the BigQuery Row() i.e.,
Row((u'exampleEmail#gmail.com', u'XXX1234XXX'), {u'email': 0, u'email_id': 1})
I need to convert this to Json, i.e.,
[{'email_id': 'XXX1234XXX', 'email': 'exampleEmail#gmail.com'}]
When running locally, I am able to just call the python Dict function on the row to transform it, i.e.,
queryJob = bigquery.Client.query(sql)
list=[]
for row in queryJob.result():
** at this point row = the BQ sample Row object shown above **
tmp = dict(row)
list.append(tmp)`
but when I load this into AWS Lambda it throws the error:
ValueError: dictionary update sequence element #0 has length 22; 2 is required
I have tried forcing it in different ways, breaking it out into sections etc but cannot get this into the JSON format desired.
I took a brief dive into the rabbit hole of transforming the QueryJob into a Pandas dataframe and then from there into a JSON object, which also works locally but runs into numpy package errors in AWS Lambda which seems to be a bit of a known issue.
I feel like this should have an easy solution but just haven't found it yet.
Try doing it like this
`
L = []
sql = (#sql_statement)
query_job = client.query(sql) # API request
query_job.result()
for row in query_job:
email_id= row.get('email_id')
email= row.get('email')
L.append([email_id, email])
`

Parameterizing the JSON Data file in the VuGen

Need some help in LoadRunner scripting in REST API. In my requirement, I'm passing the JSON file in the web_custom_request LR Function,
Following is the content of the JSON File
{"serviceLayerOperationRequest":{
"contextObjectId": "36045467715",
"payload":"{\"UserSessionSearchCriteria\":{\"os_st_id\":\"36045467715\",\"LastName\":\"test\",\"FirstName\":\"test\"}}",
"operationLabel": "CustomerSearch",
"serviceOpInvocationId": "1111111",
"sessionId": "{SessionID}"
}}
New Value is fetched from the previous response body and successfully written into the Parameter SessionID
Currently, it picks the string {SessionID}.
In the above JSON file, variable sessionId's value is dynamic, so I want to parameterize it from the Parameters. What should be the correct syntax for this?

Using JsonSlurper to parse MySQL Json output returns groovy.lang.MissingMethodException

I am currently working on a way to parse the output of a section of a MySQL query using Groovy's JsonSlurper.
I am trying to pull the LAT and LONG values from this query.
The query with the Json included reads fine into the database, with the expected values being returned, however, when I try and parse this
Json in my JsonSlurper I get a java Missing Method exception, which complains about the parseText(). The error recommends parseText as a solution,
although this is what is being used.
The error is as follows:
groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (java.util.ArrayList)
My code is as follows:
The section of the query which produces the json is as follows:
SELECT concat('{Address:"',n.address,'",LAT:"'map.details,'",LONG:"'map.details'"}') as list FROM table
I then call the list in my JsonSlurper method, which is being populated as a database field in the application:
def result = new JsonSlurper().parseText(table.list)
def latitude = result.get("LAT")
def longitude = result.get("LONG")
println latitude
println longitude
I then plan on populating these fields in a web page, but I cannot do this until I am able to return them from the parse.
The latitude and longitude values are integers, although they are parsed as strings.
The result of your query is a list of JSON strings, even if there is only one element. Use
new JsonSlurper().parseText(table.list.first())

Confused with JSON data and normal data in Django ajax request

I read about JSON from internet but still i have not got the grasp of it. I am reading this article
http://webcloud.se/log/AJAX-in-Django-with-jQuery/
I could not understood the first part where the function is using JSON
def xhr_test(request, format):
if request.is_ajax():
if format == 'xml':
mimetype = 'application/xml'
if format == 'json':
mimetype = 'application/javascript'
data = serializers.serialize(format, ExampleModel.objects.all())
return HttpResponse(data,mimetype)
# If you want to prevent non XHR calls
else:
return HttpResponse(status=400)
My Main Problems are
From where the function is getting format variable
Does format is json mean that data given to function is json or data which will be recived is json
Can anyone give me simple example that what will be the ouput of this function
data = serializers.serialize(format, ExampleModel.objects.all())
How will I use that data when i get that response in jquery function
If i don't use JSON in above function then how will the input and response back will chnage
Thanks
From where the function is getting format variable
In practice, there are lots of ways this format could be populated. HTTP provides an Accept: header that requests can use to indicate the preferred Content-Type for the response. On the client, you might use xhr.setRequestHeader('accept', 'application/json') to tell the server that you want your response in json format. In practice, though, very few frameworks actually do this. This being django, arguments to view functions are usually set in the urlconf, you might craft a urlconf like this:
urlpatterns = patterns('',
# ...
(r'^xhr_test.(?<format>.*)$', 'path.to.xhr_test'),
)
2 . Does format is json mean that data given to function is json or data which will be recived is json
This particular view doesn't do anything at all with the request body, and is certainly providing a response body in the supplied format
4 . How will I use that data when i get that response in jquery function
Depending on how complicated your request needs to be, you can use jQuery.getJSON, which will pass your callback with regular JavaScript objects that result from parsing the JSON. If you need to do a bit more work to get the request right, you can use jQuery.parseJSON to process the json data, and that will return the same JavaScript objects.
From the urlconf, just like it says in the article right below it.
The query set will be serialized as JSON.
It will be the query set represented as either XML or JSON. python manage.py shell is your friend.
You will decode it, then iterate over it.
You'll need to find some other format to serialize it in instead.