Django JSON serializable error - python

With the following code below, There is an error saying
File "/home/user/web_pro/info/views.py", line 184, in headerview,
raise TypeError("%r is not JSON serializable" % (o,))
TypeError: <lastname: jerry> is not JSON serializable
In the models code
header(models.Model):
firstname = models.ForeignKey(Firstname)
lastname = models.ForeignKey(Lastname)
In the views code
headerview(request):
header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit]
l_array = []
l_array_obj = []
for obj in header:
l_array_obj = [obj.title, obj.lastname ,obj.firstname ]
l_array.append(l_array_obj)
dictionary_l.update({'Data': l_array}) ;
return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript')
what is this error and how to resolve this?
thanks..

The quick read is that obj.lastname is a Lastname model not a String. You probably need to say something like:
l_array_obj = [..., obj.lastname.value, .... ]
to get the string value, rather than the Model object.

Have you considered using Django's own serialization functionality?

Related

Python + JSON Formatting ('list' object has no attribute 'values')

I'm getting the following error. I'm confident the error is due to my JSON formatting. How should I be formatting my JSON file?
Exception has occurred: AttributeError
'list' object has no attribute 'values'
The error is occurring on the following line
total_sites = len(custom_sites.values())
The function it's trying to execute
def get_available_websites():
string = []
with open('settings.json') as available_file:
for sites in json.load(available_file)['custom_sites']:
string.append(sites + ", ")
return (''.join(string))[:-2]
The JSON file
{
"custom_sites": [
"https://github.com",
"https://test.com"
]
}
I've tried various changes in the JSON file. Alternating [], and {}
custom_sites will be a list not a dict so it wont have a values attribute. you can just check the length of the list its self.
import json
json_str = """{
"custom_sites": [
"https://github.com",
"https://test.com"
]
}"""
custom_sites = json.loads(json_str)["custom_sites"]
total_sites = len(custom_sites)
print(f"{total_sites=}")
OUTPUT
total_sites=2

AttributeError: 'str' object has no attribute 'json'

I wrote little script on python 3.7 to receive actual browser version
Here is it:
import json
def json_open():
file_json = open('/Users/user/PycharmProjects/Test/configuration.json')
return json.load(file_json)
def get_last_version(browser_name):
f = json_open()
res = (f['global']['link_to_latest_browser_version'])
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
#print(last_version[1:-1])
return last_version[1:-1]
Also, json file exists, but it does not matter now.
Received:
AttributeError: 'str' object has no attribute 'json'.
In row
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
Please, tell me what is my mistake?
If you are trying to convert res as a json object try json.loads(res) instead of res.json()
Try this:
import json
FILEJSON = '/Users/user/PycharmProjects/Test/configuration.json'
def get_last_version(browser_name):
with open(FILEJSON, 'r') as fson:
res = json.load(fson)
last_version = res['global']['link_to_latest_browser_version']\
['latest']['client'][browser_name]['version'][1:-1]
return last_version
I think that the json_open function is unnecessary. Also take into account that the behavior of the json.load() method depends on the type of file you are reading.
Ok, the problem is here:
last_version = repr(res.json()['latest']['client'][browser_name]['version'])
A JSON object is basically a dictionary. So when you do json['key'] it returns the content, not a json object.
Here res is a string, not a json object and thus does not have the .json() attribute.
Edit:
If you want a string to be return in your situation:
res = json.loads(f['global']['link_to_latest_browser_version'])
last_version = res['latest']['client'][browser_name]['version']
return last_version
Your "res" variable is of type string.
Strings do not have an attribute called json.
So res.json() is invalid.

Django Model is not JSON serializable

Im trying to return a dictionary of Django models in JSON format.
I have tried serializers, model_to_dict, json.dump and can't seem to get it working.
a small snippet of the code:
def get_queryset(self):
queryset = (Venue.objects.all())
location = self.request.query_params.get('location', None)
latitude = location.split('S')[0]
longitude = location.split('S')[1]
venue_gaps = {}
for venue in queryset.iterator():
locationArray = [y.strip() for y in venue.postcode.split(',')]
distance = gmaps.distance_matrix([str(latitude) + " " + str(longitude)], [str(locationArray[0]) + " " + str(locationArray[1])], mode='driving')['rows'][0]['elements'][0]
m = distance["distance"]["value"]
venue_gaps[m] = venue
sorted_venues = dict(sorted(venue_gaps.items()))
return JsonResponse(json.dumps(sorted_venues))
the dictionary I create is a {int:object, int:object, int:object, ....}
I want this to be returned as the response. I keep getting issues such as "TypeError: Object of type object is not JSON serializable"
Use django.core.serializers:
from django.core import serializers
qs = YourModel.objects.filter(foo='bar')
serialized_qs = serializers.serialize('json', qs)
print(serialized_qs)
Docs: https://docs.djangoproject.com/en/2.2/topics/serialization/
Simpler issue I believe:
return JsonResponse(json.dumps(sorted_venues))
is redundant, this should work:
return JsonResponse(sorted_venues)

serializing sqlalchemy class to json

I'm trying to serialize the result (a list) of an sqlalchemy query to json.
this is the class:
class Wikilink(Base):
__tablename__='Wikilinks'
__table_args__={'extend_existing':True}
id = Column(Integer,autoincrement=True,primary_key=True)
title = Column(Unicode(350))
user_ip = Column(String(50))
page = Column(String(20))
revision = Column(String(20))
timestamp = Column(String(50))
and I guess my problem is with the __repr__(self): function.
I tried something like:
return '{{0}:{"title":{1}, "Ip":{2}, "page":{3} ,"revision":{4}}}'.format(self.id,self.title.encode('utf-8'),self.user_ip,self.page,self.revision)
or:
return '{"id"={0}, "title"={1}, "Ip"={2}}'.format(self.id,self.title.encode('utf-8'),self.user_ip.encode('utf-8'),self.page,self.revision)
and I got:
TypeError(repr(o) + " is not JSON serializable")
ValueError: Single '}' encountered in format string
I tried:
return '{id=%d, title=%s, Ip=%s}'%(self.id,self.title.encode('utf-8'),self.user_ip.encode('utf-8'))
and I got:
TypeError: {id=8126, title=1 בדצמבר, Ip=147.237.70.106} is not JSON serializable
adding "" around (according to the JSON formatting) like this: "id"="%d", "title"="%s", "Ip"="%s" didn't help either.
I know this is supposed to be dead simple but I just can't get this right
actually bottle is handling the jsonification part automatically, but trying to call json.dumps on the result gives me the same errors.
Instead of trying to convert to json a string, you could define, for example, your own to_dict method that returns the dictionary structure it seems you're trying to create and, after that, generate the json from that structure:
>>> import json
>>> d = {'id':8126, 'title':u'1 בדצמבר', 'ip':'147.237.70.106'}
>>> json.dumps(d)
'{"ip": "147.237.70.106", "id": 8126, "title": "1 \\u05d1\\u05d3\\u05e6\\u05de\\u05d1\\u05e8"}'
I'm not sure I understand what you tried. Couldn't you build the dict and let json.dumps() do the work for you?
Something like:
>>> class Foo:
... id = 1
... title = 'my title'
... to_jsonize = ['id', 'title']
>>>
>>> dct = {name: getattr(Foo,name) for name in Foo.to_jsonize}
>>> import json
>>> json.dumps(dct)
'{"id": 1, "title": "my title"}'

Serializing ReferenceProperty in Appengine Datastore to JSON

I am using the following code to serialize my appengine datastore to JSON
class DictModel(db.Model):
def to_dict(self):
return dict([(p, unicode(getattr(self, p))) for p in self.properties()])
class commonWordTweets(DictModel):
commonWords = db.StringListProperty(required=True)
venue = db.ReferenceProperty(Venue, required=True, collection_name='commonWords')
class Venue(db.Model):
id = db.StringProperty(required=True)
fourSqid = db.StringProperty(required=False)
name = db.StringProperty(required=True)
twitter_ID = db.StringProperty(required=True)
This returns the following JSON response
[
{
"commonWords": "[u'storehouse', u'guinness', u'badge', u'2011"', u'"new', u'mayor', u'dublin)']",
"venue": "<__main__.Venue object at 0x1028ad190>"
}
]
How can I return the actual venue name to appear?
Firstly, although it's not exactly your question, it's strongly recommended to use simplejson to produce json, rather than trying to turn structures into json strings yourself.
To answer your question, the ReferenceProperty just acts as a reference to your Venue object. So you just use its attributes as per normal.
Try something like:
cwt = commonWordTweets() # Replace with code to get the item from your datastore
d = {"commonWords":cwt.commonWords, "venue": cwt.venue.name}
jsonout = simplejson.dumps(d)

Categories