I am currently writing the aws lambda function with python to http post requests
apprantly its failing to serialize json headers
here my mode
import json
from botocore.vendored import requests
API_ENDPOINT = "https://api.someservices.com/v1/aws_accounts"
API_KEY = "asdfasdfasdfasdfasdf"
externalID ="dadsfasdfasdfasd"
def api_post(account_id, rolearn, account_name):
headers = {"Content-Type" : "application/json", "api_key" : API_KEY}
data = {"name":account_name,"authentication":{"protocol": "assume_role","assume_role_arn":rolearn,"assume_role_external_id":externalID}}
json_data = json.dumps(data)
response = requests.post(url = API_ENDPOINT,headers=headers, data=json_data)
print(response)
return response
this is the error I am getting
def lambda_handler(event, context):
result = update_ch(event['account_id'],event['rolearn'],event['account_name'])
return result
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: is not JSON serializable
This issue has been sorted out . I was using wrong library
Related
import requests
url = "**************"
querystring = {"domain":"gmail.com","username":"random","server":"server-1","type":"real"}
headers = {
"X-RapidAPI-Key": "******************",
"X-RapidAPI-Host": "*****************"
}
response = requests.request("GET", url, headers=headers, params=querystring).text
response:
{"code":200,"msg":"OK","items":{"email":"vinhvivyanvinh72943#gmail.com","timestamp":1659215390}}
.
print(response['items'])
TypeError: string indices must be integers
Hello,
I do not encounter any problems when I use it in another dictionary.
How can I get email and timestamp into variables?
Use .json() on request response:
response = requests.request(
"GET", url, headers=headers, params=querystring
).json() # <-- note the .json()
print(response["items"]["email"], response["items"]["timestamp"])
I am using Requests HTTP library. I am trying to simple print HTML of the requested page.
Here is my payload string, I tried with decode('utf-8') but it doesn't work:
import json
import requests
url = "http://ec.europa.eu/eures/eures-searchengine/page/jvSearch/search?lang=de&app=1.3.1p1-build-0"
countryName = "ÖSTERREICH".decode('utf-8')
payload = '{"keywords":[{"keyword":"","specificSearchCode":"EVERYWHERE"}],"locationCriteriaBean":{"selectedNuts":[{"id":1231,"nutsCode":"AT","parentNutsId":None,"countryId":1,"label":"%s","nutsLevel":0,"regions":[]}],"notSpecifiedInCountry":[]},"selectedOccupations":[],"contractTypeCodes":[],"contractDurationCodes":[],"experienceCodes":[],"educationLevelCodes":[],"euresFlagCodes":[],"page":1,"resultsPerPage":50,"publicationDate":"LAST_MONTH","sortSearch":"REPLICATION_DATE_DESCENDING"}'% countryName
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print r.status_code
I am getting 500. Can some one tell me what should I do for that?
The following is what GitHub returns from a REST GET method. How to parse it using JSON?
response.success = { resp, reader ->
result = reader.text
}
[{"login":"ghost","id":1,"avatar_url": ....},{"login":"github-enterprise","id":2,"avatar_url": ....}]
You can use awesome tool for working with json - json slurper:
def slurper = new JsonSlurper()
def result = slurper.parseText(result)
def firstLogin = result[0].login
def secondId = result[1].id
I have the following Groovy script (not a Grails app) that is returning a JSON-like, but it is not strictly valid JSON.
String baseURL = 'https://test.com'
File userFile = new File("./user.json")
def client = new HTTPBuilder(baseUrl)
client.headers['Content-Type'] = 'application/json'
client.request(GET, JSON) { req ->
requestContentType = JSON
headers.Accept = 'application/json'
response.success = { resp, json ->
userFile.append json.toString()
println JsonOutput.toJson(json.toString())
}
}
I am trying to create a JSON output file. I have tried using JsonOutput.prettyPrint and I looked at JsonBuilder, but that looks like I would have to build the JSON structure manually when Groovy should support the output. This is what I am getting back.
{AssetNumber=AssetNumber1, DeviceFriendlyName=FriendlyName1, PhoneNumber=17035551231, SerialNumber=SerialNumber1, Udid=Udid1, UserEmailAddress=user1#email.com, UserId=userId1, UserName=userName1}
As I said, this is JSON-like, but not strictly valid. I was expecting something like:
{"AssetNumber": "AssetNumber1", "DeviceFriendlyName": "FriendlyName1"....}
Any ideas?
It works perfectly fine (groovy v 2.3.6):
import groovy.json.*
def pretty = JsonOutput.prettyPrint(JsonOutput.toJson([1:2]))
assert pretty == """{
"1": 2
}"""
In this closure:
response.success = { resp, json ->
userFile.append json.toString()
println JsonOutput.toJson(json.toString())
}
You're getting an instance of Map under json variable. You do not need to turn it into a string. Instead use:
userFile.append JsonOutput.toJson(json)
println JsonOutput.toJson(json)
I have a Grails service that sends a request to the JIRA REST API and returns JSON - When I try to use JsonSlurper to parse the JSON, I get the following error:
ERROR errors.GrailsExceptionResolver - JsonException occurred when processing request: [GET] /osmDash/jira/storyComplete
Lexing failed on line: 1, column: 1, while reading 'j', no possible valid JSON value or punctuation could be recognized.
Here is the code in the controller:
def jsonFile = jiraService.fetchJQL('issuetype=Story AND status in (Resolved,Closed,Done) AND resolved>=-30d') as JSON
def jiraSlurper = new JsonSlurper()
def jiraResult = jiraSlurper.parseText('jsonFile').total
And this is what the JSON looks like when I render it in the page:
{"total":1356,"issues":[],"startAt":0,"maxResults":0}
I was looking at groovy.json.JsonSlurper parse JSON, which seems simliar, but I couldn't get this method to work. I'm looking specifically to assign the "total" value to a variable.
This is the service that is returning the JSON:
def fetchJQL(String jql, Integer maxResults = 0, def fields = null) {
jira.request(POST, JSON) { req ->
uri.path = '/rest/api/2/search'
headers.'Authorization' = authHash
body = [jql: jql, maxResults: maxResults, fields: fields]
response.success = { resp, json ->
return json
}
response.failure = { resp ->
println resp.statusLine.statusCode
println resp.statusLine
}
}