How to make JSON response like this? - python

For a flask based python API project, I have to return the json response like below:
{
"images":
[
{
"transaction":
{
"message": "match found",
"status": "success",
"subjectId": 79,
"confidence": 0.56
}
}
]
}
In above json, images looks like a list and transaction looks like a dict which means that the response is list of dict. Now below is the code I have in order to achieve above format:
#app.route('/api/v1/face/recognize', methods=['POST'])
def recognize():
"""
SOME CODE
"""
images = []
transaction = dict()
transaction['status'] = 'success'
transaction['message'] = "match found"
transaction['subjectId'] = 79
transaction['confidence'] = 0.56
images.append(transaction)
return jsonify(images), 200
But it is giving me below response:
[
{
"confidence": 0.56,
"message": "match found",
"status": "success",
"subject_id": 79
}
]
which doesnt looks like what I wanted. I am unable to understand how can I make the response format look like the above mentioned. Can anyone please help. Thanks

You are very close. use images.append({'transaction': transaction})
Ex:
#app.route('/api/v1/face/recognize', methods=['POST'])
def recognize():
"""
SOME CODE
"""
images = []
transaction = dict()
transaction['status'] = 'success'
transaction['message'] = "match found"
transaction['subjectId'] = 79
transaction['confidence'] = 0.56
images.append({'transaction': transaction})
images = {'images': images}
return jsonify(images), 200
Output:
{'images': [{'transaction': {'confidence': 0.56,
'message': 'match found',
'status': 'success',
'subjectId': 79}}]}

Related

Amadeus Flight Availabilities in Python - Error 400

I am trying to use the POST method of Amadeus flight availabilities API on Python, but is is still giving me error 400. Any suggestions? Many thanks.
from amadeus import Client, ResponseError, Location
import requests
amadeus = Client(
client_id='My ID',
client_secret='My Secret')
try:
flights = amadeus.get('/v2/shopping/flight-offers',originLocationCode = "GIG",destinationLocationCode = "ATL",departureDate = "2023-01-31",nonStop = "true",travelClass = "BUSINESS",adults = 1)
body = flights.data[0]
print(body)
except ResponseError as error:
print(error)
try:
availability = amadeus.post('/v1/shopping/availability/flight-availabilities', body)
print(availability.result)
except ResponseError as error:
print('headers: ', error.response.request.headers)
print('body: ', error.response.request.params)
As per their API documentation, the body of the second API call needs to be in the following format:
{
"originDestinations": [
{
"id": "1",
"originLocationCode": "BOS",
"destinationLocationCode": "MAD",
"departureDateTime": {
"date": "2021-11-14",
"time": "21:15:00"
}
}
],
"travelers": [
{
"id": "1",
"travelerType": "ADULT"
}
],
"sources": [
"GDS"
]
}
Right now you are just feeding the second call the return from the first, which doesn't seem to be what they're looking for.
You might also need to feed the proper headers, something like:
headers = {"Content-Type": "application/json; charset=utf-8"}
then you would do
response = requests.post(url, headers=headers, json=body)

How to count value occurrences in json response using python?

I have a json response that looks like below and I would like to count how many times corrId has been mentioned.
{
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":true
}
}
For the above, I would expect result to be 3
I have tried something like above, but it throws an error:
r = requests.get(url = HOSTNAME + endpoint, headers = headers, verify=False)
data = json.loads(r.text)
corrList = len(data['corrList'][0]['corrId'])
print (corrList)
My error:
TypeError: object of type 'int' has no len()
Would someone be able to help? thanks in advance!
You need to actually count the number of dicts that have that key:
data = {
"result":
{
"corrList":[
{
"corrId":123456,
"title":"sample1",
},
{
"corrId":45678,
"title":"sample2",
},
{
"corrId":987654,
"title":"sample3",
}
],
"find":True
}
}
corrList = [item for item in data['result']['corrList'] if 'corrId' in item]
print(len(corrList))
Output 3

copying data from json response [Python]

I have a scenario where I am trying to extract data from json response which is obtained from the GET request and then rebuilding the json data by changing some values and then sending a PUT request at same time after rebuilding the json data(i.e, after changing idter value)
below is the target json response.
target_json = {
"name": "toggapp",
"ts": [
1234,
3456
],
"gs": [
{
"id": 4491,
"con": "mno"
},
{
"id": 4494,
"con": "hkl"
}
],
"idter": 500,
"datapart": false
}
from the above json I am trying to change the idter value to my custom value and rebuild it into json data again and post the new json data.
Here is what I have tried :
headers = {'Authorization': 'bearer ' + auth_token, 'Content-Type':'application/json', 'Accept':'application/json'}
tesstid =[7865, 7536, 7789]
requiredbdy = []
for key in testid:
get_metadata_targetjson= requests.get('https://myapp.com/%s' %key, headers = headers)
metadata=get_metadata_target.json()
for key1 in metadata:
requiredbdy.append(
{
"metadata" : [{
"name": key1['name'],
"ts": key1['ts'],
"gs": key1[gs],
"idter": 100, #custom value which I want to change
"datapart": false
} ]
}
)
send_metadata_newjson= requests.put('https://myapp.com/%s' %key, headers = headers data = requiredbdy)
print(send_metadata_newjson.status_code)
Is this approach fine or How do I proceed in order to achieve this scenario.
You can use the built-in json module for this like so
import json
my_json = """
{
"name": "toggapp",
"ts": [
1234,
3456
],
"gs": [
{
"id": 4491,
"con": "mno"
},
{
"id": 4494,
"con": "hkl"
}
],
"idter": 500,
"datapart": false
}
"""
json_obj = json.loads(my_json)
json_obj['idter'] = 600
print(json.dumps(json_obj))
Prints
{"name": "toggapp", "ts": [1234, 3456], "gs": [{"id": 4491, "con": "mno"}, {"id": 4494, "con": "hkl"}], "idter": 600, "datapart": false}
There's this small script used it to find entries in some very long and unnerving JSONs. not very beautifull und badly documented but maybe helps in your scenario.
from RecursiveSearch import Retriever
def alter_data(json_data, key, original, newval):
'''
Alter *all* values of said keys
'''
retr = Retriever(json_data)
for item_no, item in enumerate(retr.__track__(key)): # i.e. all 'value'
# Pick parent objects with a last element False in the __track__() result,
# indicating that `key` is either a dict key or a set element
if not item[-1]:
parent = retr.get_parent(key, item_no)
try:
if parent[key] == original:
parent[key] = newval
except TypeError:
# It's a set, this is not the key you're looking for
pass
if __name__ == '__main__':
alter_data(notification, key='value',
original = '********** THIS SHOULD BE UPDATED **********',
newval = '*UPDATED*')

How to parse musixmatch python api JSON response?

How do you parse the JSON response from the musixmatch api?
I'm calling the method
res = artist_api.artist_search_get(format=format, q_artist=artist)
I'm getting a response of
{'message': {'body': {'artist_list': [{'artist': {'artist_alias_list': [],
'artist_comment': '',
'artist_country': '',
'artist_credits': {'artist_list': []},
'artist_edit_url': None,
'artist_id': 26575484.0,
'artist_mbid': None,
'artist_name': 'Illenium',
'artist_name_translation_list': [],
'artist_rating': 55.0, .........
I'm trying to get the artist_id.
I tried getting the artist_id like this:
print(res['message']['body']['artist']['artist_id'])
artist_api = swagger_client.ArtistApi()
format = 'json'
try:
artist_list = ["adele", "lady gaga", "john legend"];
for artist in artist_list:
print(artist)
res = artist_api.artist_search_get(format=format, q_artist=artist)
print(res['message']['body']['artist']['artist_id'])
except ApiException as e:
print "Exception when calling ArtistApi->artist_search_get: %s\n" % e
I'm getting this error message:
Traceback (most recent call last):
File "musixmatch.py", line 39, in <module>
print(res['message']['body']['artist_id'])
TypeError: 'InlineResponse2004' object has no attribute '__getitem__'
Please help I've searched through a bunch of threads but I still can't find the answer to this. I'm new to python so I'm not sure what I'm doing wrong.
You a little messed up with the hierarchy of JSON-document, use this code to get desired values:
[artist['artist']['artist_id'] for artist in res['message']['body']['artist_list']]
As an alternative, can be used JSONPath-expression: $..artist_list..artist_id to get the same result.
Example
from jsonpath_rw import parse
import json
res = json.loads("""{
"message": {
"header": {},
"body": {
"artist_list": [
{
"artist": {
"artist_credits": { },
"artist_country": "string",
"artist_id": 110
}
},
{
"artist": {
"artist_credits": {},
"artist_country": "string",
"artist_id": 220
}
}
]
}
}
}""")
# 1-way: Iterate through JSON-document
print([artist['artist']['artist_id'] for artist in res['message']['body']['artist_list']])
# result: [110, 220]
# 2-way: Use JSONPath-expression
jsonpath_expr = parse('$..artist_list..artist_id')
print([match.value for match in jsonpath_expr.find(res)])
# result: [110, 220]

Aws Lambda function returns confidence 99% to anything i upload

I am doing some thing wrong over here, while comparing two images in different S3 Bucket.
Even though, I am comparing images of male and female it would give 99% confidence
or am i missing something in the declaration yet
Maybe This line is causing a problem
key_target = "targett/" + key
Or my event code is error prone this is where i have mentioned my source bucket ,even though i have mentioned it in lambda function for testing below. What else do i need to correct so that it will return the confidence within the rang specified
from __future__ import print_function
import boto3
from decimal import Decimal
import json
import urllib
print('Loading function')
rekognition = boto3.client('rekognition')
#iot = boto3.client('iot-data')
# --------------- Helper Functions to call Rekognition APIs ------------------
def compare_faces(bucket, key, key_target, threshold=75):
response = rekognition.compare_faces(
SourceImage={
"S3Object": {
"Bucket": 'dacss',
"Name": 'obama.jpg',
}
},
TargetImage={
"S3Object": {
"Bucket": 'targett',
"Name": 'michelle.jpg',
}
},
SimilarityThreshold=threshold,
)
return response['SourceImageFace'], response['FaceMatches']
# --------------- Main handler ------------------
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']
['key'].encode('utf8'))
key_target = "targett/" + key
try:
response = compare_faces(bucket, key, key_target)
print(response)
# mypayload = json.dumps(response)
# iotResponse = iot.publish(
# topic="rekognition/result",
# qos=1,
# payload=mypayload)
# print(iotResponse)
# return iotResponse
print(response)
return response
except Exception as e:
print(e)
print("Error processing object {} from bucket {}. ".format(key,
bucket)
+
"Make sure your object and bucket exist and your bucket is in
the
same region as this function.")
raise e
---------------output-----------------
Response:
[
{
"BoundingBox": {
"Width": 0.7813892960548401,
"Top": 0.15193353593349457,
"Left": 0.1047489121556282,
"Height": 0.8365015387535095
},
"Confidence": 99.99993896484375
},
[]
]
i think you are having some misunderstanding here
{
'FaceMatches': [
{
'Face': {
'BoundingBox': {
'Height': 0.33481481671333313,
'Left': 0.31888890266418457,
'Top': 0.4933333396911621,
'Width': 0.25,
},
'Confidence': 99.9991226196289,
},
'Similarity': 100,
},
],
'SourceImageFace': {
'BoundingBox': {
'Height': 0.33481481671333313,
'Left': 0.31888890266418457,
'Top': 0.4933333396911621,
'Width': 0.25,
},
'Confidence': 99.9991226196289,
},
'ResponseMetadata': {
'...': '...',
},
}
Here the confidence score does'nt show weather the face matches or not it shows that it found the face in the image. "Similarty" shows the actual match of the image.
These lines:
TargetImage={
"S3Object": {
"Bucket": targett,
"Name": obama.jpg,
}
should be:
TargetImage={
"S3Object": {
"Bucket": 'targett',
"Name": key_target,
}

Categories

Resources