getting object has no attribute 'get' or object is not subscriptable when trying to access JSON response converted to DTO - python

I'm trying to access a JSON response, I've trying with get() method and I'm getting the "object has no attribute 'get'" error and when I tried it with [] I'm getting the "object is not subscriptable" error.
The response is valid, as I've printed it just before the get operation and all looks ok.
Did not had such problem parsing a response before.
def get_return_params_and_identifiers(return_params):
print("******** res start **********")
print(return_params)
print("******** res end **********")
return_parameters = return_params.get('return_parameters')
Here is part of a response:
******** res start **********
{'levels': None,
'return_parameters': [{'identifier_name': 'Premium',
'level': None,
'return_parameter_name_pk': 1258407,
'return_parameters_details': [{'base_parameter_name': 'Premium '
'Parameter',
'base_parameter_pk': 1149913,
'class_value': None,
....
....
Did anybody encountered such and have any idea what is happening.
EDIT:
Tried with json.loads() but the response is a DTO and not JSON anymore and thus getting the other error:
TypeError: the JSON object must be str, bytes or bytearray, not DTO
The DTO class is below:
class ReturnParametersContainerDTO(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'return_parameters': 'list[ReturnParameterDTO]',
'levels': 'LevelsDTO'
}
attribute_map = {
'return_parameters': 'returnParameters',
'levels': 'levels'
}
It clearly says that the items in the class are dictionary, but somehow it does not recognize it.

Ok, I solved the issue.
It was something in the implementation of the OpenApi's generated DTO class, that showed it as a dictionary (in to_str() method it called to_dict() and prints it as a dictionary) but in fact those were just properties, so used the method to_dict() (in swagger's generated class) to convert it to dictionary.
Now all works.

Related

errors parsing json objects using python3.7, unable to access key values

I have a python lambda function which receives posted data. The function looks a bit like this:
import json
import ....
def handle(event, context):
if event["body"]:
posted_data = json.loads(event["body"])
print(posted_data)
print(posted_data["email"])
print(posted_data.get("email"))
The line print(posted_data) prints my json object like this:
{
"tel": "078723646",
"message": "jsd fljxdisfbv lskdjnildufv nlksjfg",
"email": "my#selg.om"
}
The line print(posted_data["email"]) gives me this error:
[ERROR] TypeError: string indices must be integers
The line print(posted_data.get("email") give this error:
[ERROR] AttributeError: 'str' object has no attribute 'get'
Yet, when I open a console, run python, and do this:
>>> obj = {"tel": "078276353", "message": "uisdjy df jdslfj lsdjf fb", "email": "tetet#gdgdg.lo"}
>>> type(obj)
The response I get is:
<class 'dict'>
So, I'm a little confused as to whether it's a dictionary or a string.
What I need to do is to access each of the values in the object.
I tried this, but that had the effect of reversing the json.loads
I also looked here, but that did not assist. I checked this but it doesn't seem to be relevant to my case.
After a suggestion from #brunns I inserted print(type(posted_data)) after posted_data = json.loads(event["body"]) and discovered that posted_data is in fact a string.
I was expecting json.loads(event["body"]) to convert the json object to a python object. How do I go about retrieving the values in the object?

Python intermittently throws "AttributeError: 'NoneType' object has no attribute 'get'" on the same dictionary

I have a nested dictionary like so:
mail = {
'data': { 'from': {'text': '123#example.com'}}
# some other entries...
}
I'm trying to copy from value using following code:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from').get('text')
The second line throws the exception:
AttributeError: 'NoneType' object has no attribute 'get'
The strange thing is, this only happens sometimes. If I add a print statement just before the second line like:
data = mail.get('data')
print(type(data.get('from')))
new_dict['parse']['from'] = data.get('from').get('text')
The error disappears and I get <class 'dict'> as expected. If I remove the print statement, it works sometimes and other times it throws the error. Nothing else changes in the code or data. The reason I'm using get() is to retrieve value safely in case the key is missing.
In the call data.get('from').get('text'), if data does not contain the key 'from', it will return None. None.get('text') raises then the exception you see, because a None object has no get method (of course).
The way around this is to pass in a better default-object than None (the default default-object), which has the get method. That would be an empty dictionary, {}:
data = mail.get('data')
new_dict['parse']['from'] = data.get('from', {}).get('text')

Getting Django object "is not JSON serializable"

I have a webservice that reads a JSON object and it was giving me unicodeEncodeError exception. After googling a little bit, I saw How can I convert a dict to a unicode JSON string?
(I followed other questions that were related to unicodeEncodeError but I was still getting AttributeError: 'dict' object has no attribute 'content')
I did what was mentioned in that particular question and now I am getting ..... is not JSON serializable
Can anyone tell me what do I have to do now?
Following is my code:
def someMethod()
some_data = request.data
json_string1 = json.dumps(some_data) #GETTING ERROR ON THIS LINE
json_string2 = get_string(json_string1)
archive = call.send_json(json_string2)
def get_string(value):
find_unicode = re.compile('\\\\u([\da-f]{4})')
def get_parsed_unicode(x):
return chr(int(x.group(1), 16))
return find_unicode.sub(get_parsed_unicode, str(value))
Thanks for the help !!
When you're passing the object to the method, use foo.serealize(true). Include JQUERY to use this.

unexpected attribute error in python object

I'm parsing objects returned by the suds client from a Web Services SOAP API
I have a list of attributeObjects, like
(defectStateAttributeValueDataObj){
attributeDefinitionId =
(attributeDefinitionIdDataObj){
name = "Comment"
}
attributeValueId =
(attributeValueIdDataObj){
name = "Owner changed because of default owner assignment specified in the component map"
}
}
and
(defectStateAttributeValueDataObj){
attributeDefinitionId =
(attributeDefinitionIdDataObj){
name = "OwnerName"
}
attributeValueId =
(attributeValueIdDataObj){
name = "Schmoe, Joe"
}
}
I use the following loop to extract key/value pairs:
for defect in myDefectsPage.mergedDefects :
print defect.cid,
for attribute in defect.defectStateAttributeValues:
print attribute
attr= attribute.attributeDefinitionId.name
val=attribute.attributeValueId.name
print attr,'=',val,
print ""
(The above objects are results of the print attribute command)
This will work as expected for EVERY attribute, except the one where attribute.attributeDefinitionId.name == "Comment"
for that one I get the
Traceback (most recent call last):
File , line 63, in
val=attribute.attributeValueId.name
AttributeError: 'Text' object has no attribute 'name'
which is strange, because if I use
val=attribute.attributeValueId #.name
it will print
Commment = (attributeValueIdDataObj){
name = "Owner changed because of default owner assignment specified in the component map"
}
So it looks like it IS an attributeValueIdDataObj and DOES have a name attribute.
I used the suds DEBUG logging and the XML return elements look exactly the same regardless of what the attribute.attributeDefinitionId.name is.
I have no idea how it changes into a 'Text' object when trying to access the name attribute
Any ideas?
On further examination (and printing out the type of the returned object when exception happened) this was a bug in the web services SOAP server.
When a Comment was empty, it returned an
<attributeValueId/>
tag,
instead of the proper
<attributeValueId>
<name/>
</attributeValueId>
object. so it resulted in sax.Text object instead of the suds.attributeValueIdDataObj object
So no python or suds mystery to solve.
Sorry for the false alarm...

Calling AWS lambda function with Inner class input type

I defined my lambda function like this and uploaded it to Amazon:
#Override
public String handleRequest(Request input, Context context) {
String template = "%s ${greeting}";
StrSubstitutor ss = new StrSubstitutor(input.replaceables);
String inputted = String.format(template, input.rawValues[0]);
return ss.replace(inputted);
}
The request class definition (Inner class):
public class Request {
String[] rawValues;
HashMap<String, String> replaceables;
public Request(){
replaceables = new HashMap<String, String>();
}
//...getter and setters
}
Then call it from boto3 and get this answer:
>>> client = boto3.client('lambda', 'us-west-2')
>>> resp = client.invoke(FunctionName='myfunction', InvocationType='RequestResponse', Payload="""{"rawValues": ["jero"], "replaceables": {"greeting": "world"}}""")
>>> resp['Payload'].read()
'{"errorMessage":"An error occurred during JSON parsing","errorType":"java.lang.RuntimeException","stackTrace":[],"cause":{"errorMessage":"com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class mypackage.functions.Demo$Request]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)\\n at [Source: lambdainternal.util.NativeMemoryAsInputStream#735b478; line: 1, column: 2]","errorType":"java.io.UncheckedIOException","stackTrace":[],"cause":{"errorMessage":"No suitable constructor found for type [simple type, class mypackage.functions.Demo$Request]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)\\n at [Source: lambdainternal.util.NativeMemoryAsInputStream#735b478; line: 1, column: 2]","errorType":"com.fasterxml.jackson.databind.JsonMappingException","stackTrace":["com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)","com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1080)","com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)","com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:142)","com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1441)","com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1047)"]}}}'
Complete Error as shown when testing in amazon console:
"cause": {
"errorMessage": "No suitable constructor found for type [simple type, class mypackage.functions.Demo$Request]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)\n at [Source: lambdainternal.util.NativeMemoryAsInputStream#2c9f9fb0; line: 1, column: 4]",
"errorType": "com.fasterxml.jackson.databind.JsonMappingException",
"stackTrace": [
"com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)",
"com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1080)",
"com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:295)",
"com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:142)",
"com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1441)",
"com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1047)"
]
}
So the main error returned is making me think that there is a problem with my Request class definition which basically defines the recipient for an unserialized JSON """{"rawValues": ["jero"], "replaceable": {"greeting": "world"}}""". In the documentation, it is stated that Map java type is supported as input type but I can not get this working. Do you know o any example of a java function mapping JSON dictionaries to Java Maps?
Non-static inner classes can't be constructed from outside an instance of the outer class.
Try making the inner class (Request) static, like:
public static class Request {
...
}

Categories

Resources