How to serialize an object - python

i have a method that does some calculations and must return a dictionary as shown below in the code section.
the method can not return the dictionary as it contains non serialized data.
i tried to enocod it as explained in the link below
https://pynative.com/online-python-code-editor-to-execute-python-code/
and her as well
TypeError: Object of type 'float32' is not JSON serializable
but i still receive the same error message.
please let me know how to solve this issue
code:
resultsDict = {
"pixelsValuesSatisfyThresholdInWindowSegment":json.dumps(numpyData,cls=NumpyArrayEncoder),
...
...
...
}
return resultsDict
error message
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type float32 is not JSON serializable

I just did the following
resultsDict =
{"pixelsValuesSatisfyThresholdInWindowSegment":str(pixelsValuesSatisfyThresholdInWindowSegment)
}
and it is working.

Related

TypeError: a bytes-like object is required, not '_io.BufferedReader' : While passing file in the request parameter

I want to pass xlsx file as one of the request parameters (file) as below.
fields = {
"file": ('1.xlsx',open("file.xlsx", "rb"),'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
"payload" : ""
}
But when I am passing a file like above I am getting this exception or error in python:
TypeError: a bytes-like object is required, not '_io.BufferedReader'
Can anyone help on this.
open() just opens the file for reading, you need to actually read the file bytes. Cannot tell fully from limited context, but if you don't need base64 then just drop that part out. The MIME type for binary data is "application/octet-stream"
Try this:
import base64
with open("file.xlsx", "rb") as xl_file:
fields = {
"file": ('1.xlsx',base64.encodestring(xl_file.read()),'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
"payload" : ""
}
# do something with fields

Why does python protobuf json_format.Parse throw a TypeError?

I am experimenting with protobuf serialization to JSON. I made a simple proto file with the following messages:
syntax = "proto3";
message Bool {
bool data = 1;
}
message BoolArray {
repeated Bool bools = 1;
}
I then run some basic code to build the message, push to Json, then read it back in:
pb_bool_array = pb_bool.BoolArray()
b = pb_bool_array.bools.add()
b.data = True
bools_as_json = MessageToJson( pb_bool_array )
Parse(bools_as_json, proto.bool_pb2.BoolArray )
but the Parse function throws a TypeError with the following message:
google.protobuf.json_format.ParseError: Failed to parse bools field:
unbound method ClearField() must be called with BoolArray instance as
first argument (got str instance instead).
I traced the Parse function and this error fires off on line 519 in Google's json_format code. Why would this TypeError occur? Am I missing something in my proto spec and/or abusing the python API?
Thanks!
After further analysis of the json_format.Parse() function, I realized that I was abusing the API.
Parse(bools_as_json, proto.bool_pb2.BoolArray )
should really be:
Parse(bools_as_json, proto.bool_pb2.BoolArray() )
The API expects a message instance to fill, not the type of message. Everything works as expected.

AttributeError: 'bytes' object has no attribute '__dict__'

I totally new in Python and stuck with this error:
I am trying to encode an image and then convert it to json to upload into a no-sql db. But when I am trying to convert it to json I am getting this error:
"AttributeError: 'bytes' object has no attribute 'dict'"
Below is my python code:
import base64
import json
def jsonDefault(object):
return object.__dict__
with open("img123.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print(str)
json_str = {'file_name':'img123','img_str':str}
pytojson = json.dumps(json_str, default=jsonDefault)
print(pytojson)
That happens because you are trying to access a property that a bytes object doesn't have (__dict__). I understand that you need to return a format that can be serialized to JSON.
This works for me, but I don't know if it's the decoding you desire:
def jsonDefault(o):
return o.decode('utf-8')
See TypeError: b'1' is not JSON serializable as well.

Can't get the value from a JSON object using Python

import requests
import json
s = requests.Session()
s.params["key"] = "MY_KEY"
s.params["cx"] = "MY_CX"
s.params["num"] = 1
result = s.get('https://www.googleapis.com/customsearch/v1', params={"q": "Search query"})
Everything is working fine and I do get a result back but it's JSON. What I want is one thing. Since my result only gives 1 search result, I want the link of that search result. From I've understood that link value is under the keys "item" and then "link". I've tried lots of things but I keep getting either one of these errors below.
TypeError: 'Response' object is not subscriptable
NameError: name 'json' is not defined
AttributeError: 'Response' object has no attribute 'read'
TypeError: the JSON object must be str, not 'Response'
What am i doing wrong and what's the solution?

TypeError: object of type 'instancemethod' has no len()

I'm finish cleaning my project. I remove not useful apps and codes then I arrange them. After this I encountered error
TypeError: object of type 'instancemethod' has no len()
so I change it to count() but I encountered error again
AttributeError: 'function' object has no attribute 'count'
Here is my code:
def budget(request):
envelopes = Envelope.objects.filter(
user=request.user).exclude_unallocated
return render(request, 'budget.html', {
'limit': account_limit(request, 15, envelopes),
}
def account_limit(request, value, query):
count_objects = len(query)
//other codes here
return result
I think I delete something here that's why I'm getting the error
You forgot to put ()
envelopes = Envelope.objects.filter(user=request.user).exclude_unallocated()

Categories