Python: list to JSON - python

I am trying to use Django with jquery UI autocomplete but having trouble sending response.
Here is my code:
def ajax_tags_autocomplete(request):
""" Autocomplete for tag list """
beginning_of_title = request.GET.get('term', '')
tags_found = Tag.objects.values_list('title', flat=True).filter(title__startswith=beginning_of_title)
return HttpResponse(json.dumps(tags_found), mimetype='application/json')
I get an error:
[u"php"] is not JSON serializable
Why? It is not possible to serialize a list? What should I pass to the serializer, then?
I would be greatful for any advice.

Are you sure it's actually a list containing unicode objects and not a list containing some database objects? The u"php" might just be the repr() of the object.
Try json.dumps([unicode(t) for t in tags_found]) or json.dumps(map(unicode, tags_found))

Related

Understanding jsonify() function. Maybe it's used for displaying the contacts?

I have to build, in python, an address book of contacts using a json file. So, I have to define a class Contact which has as attributes hust the name, surname and mail. In the solution there is a function that I never would have thought of: jsonify(self). I don't understand what it does and why I need it. Someone can help me figure it out?
def jsonify(self):
contact = {'name':self.name,'surname':self.surname,'mail':self.mail}
return contact
Using the json library, you can convert objects into JSON really easily, but it needs to know how to go about converting them. The library doesn't know how to interpret your custom class:
>>> import json
>>> contact = Contact("Hello", "World", "hello#world.com")
>>> contact_json = json.dumps(contact)
TypeError: Object of type 'Contact' is not JSON serializable
(json.dumps(obj) converts its input to JSON and returns it as a string. You can also do json.dump(obj, file_handle) to save it to a file).
A dictionary is a known type in Python, so the json library knows how to convert it into json format:
>>> import json
>>> contact = Contact("Hello", "World", "hello#world.com")
>>> contact_json = json.dumps(contact.jsonify())
{
"name": "Hello",
"surname": "World",
"mail": "hello#world.com"
}
Using that jsonify method, you're converting the fields from your class into something that the json library can understand and knows how to translate.
This is a quick and easy way to serialise your object into JSON, but isn't necessarily the best way to do it - ideally you'd tell the JSON library how to interpret your class (see this related question: How to make a class JSON serializable).
Edit: Seeing the comment discussion - I'm assuming here you have an understanding of Python data structures and classes. If this is not the case it's worth reading up on those first.

Added escaped quotes to JSON in Flask app with mongoDB

I am trying to create API for my Flask project. I have data stored in mongoDB and for building API I am using flask_restful. The problem is that in JSON are added escaped quotes and I cannot figure why and I rather have my JSON without them.
This is how my get function looks like:
from flask_restful import Resource
import json
from bson import json_util
class Harvests(Resource):
def get(self):
json_docs = []
for doc in db.collection.find():
json_doc = json.dumps(doc, default=json_util.default)
json_docs.append(json_doc)
return json_docs
In app.py it is just like that
api = Api(app)
api.add_resource(Harvests, '/api/harvests')
And I get JSON with escaped quotes (in browser or with curl)
[
"{\"_id\": {\"$oid\": \"5c05429cc4247917d66163a7\"},...
]
If I try this outside Flask (print JSON from mongo) and it works just fine. I tried use .replace(), but I think is not most elegant solution, but it did not work anyway. Any idea how I should get rid off these backslashes?
What you see is absolutely what you should expect to see according to your code, so I think there is a misunderstanding at some point. Let me explain what you are doing.
You convert each doc (a data structure) into a jsonified version (a string) of this data. Then you gather these strings in a list. Later you see this list, and of course you see a list of strings. Each of these strings contains a jsonified version of a data structure (a dictionary with opening braces, keys and values inside, and each key is a string itself with quotes, so these quotes are escaped within the jsonified string).
I recommend to collect your documents into a list and then convert that list to json instead:
def get(self):
docs = []
for doc in db.collection.find():
docs.append(doc)
return json.dumps(docs, default=json_util.default)
This way you get one json string representing the list of docs.
Maybe your framework is already applying a jsonifying automatically, in this case just don't do this step yourself:
return docs
Just use this instead.

How can I use Json as Django view context

I have a string like:
daily_program = "{"Training Set":["abc","dxf","gfh"],"Nutrition Set":["acd","dbd","cdf"]}"
I want to use it as a context dictionary and pass it to the template in Django. Such as:
def program(request):
context = json.loads(daily_program)
return render_to_response('program.html',context,RequestContext(request))
Its acting like python Dict. when I print out the result. But I cant use it as a context in template such as:
<div>{{Training}}</div>
Is there any way to is use json object as a context dictionary ?
dialy_program should read like so, with single quotes '' to avoid a syntax error with building the string:
daily_program = '{"Training":["abc","dxf","gfh"],"Nutrition":["acd","dbd","cdf"]}'

TypeError: documents must be a non-empty list

I'm doing a program using Twitter API and MongoDB in 2.7 Python language.
I get a timeline and put it in a dictionary, which I want to store in a MongoDB database. To do this I have next code:
def saveOnBD(self, dic):
client = MongoClient("xxxx", "port")
db = client.DB_Tweets_User_Date
collection = db.tweets
collection.insert_many(dic)
I'm debbuging and dic it's not empty but I get next error:
TypeError: documents must be a non-empty list
How can I fix it?
I trying many options, but i solved that question changing the post method.
Instead of:
collection.insert_many(dic)
I used this:
collection.insert_one(dic)
I supose that, as I try to post only a variable(dic) and "insert_many()" is for many variables that retun me the error. That change solved me the question
you can either put in an entry before running the bulk entry function or use insert()
A list of documents must be passed to insert_many method
E.g.:
collection.insert_many([dic])

Creating json array in django

I am trying to make a json array in django but I am getting error -
In order to allow non-dict objects to be serialized set the safe parameter to False
and my views.py -
def wall_copy(request):
if True:
posts = user_post.objects.order_by('id')[:20].reverse()
return JsonResponse(posts)
Basically user_post is a model a posts is the object of top 20 saved data. I want to send a json array but I am unable to convert posts into a json array. I also tried serializers but it didnt helped.
I am stuck help me please.
Thanks in advance.
Would this solve your problem?
from django.core import serializers
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
posts_serialized = serializers.serialize('json', posts)
return JsonResponse(posts_serialized, safe=False)
You can solve this by using safe=False:
def wall_copy(request):
posts = user_post.objects.all().order_by('id')[:20].reverse()
return JsonResponse(posts, safe=False)
Note that it's not really unsafe - you just have to make sure on your own, that what you are trying to return can be converted to JSON.
See JsonResponse docs for reference.
Try to use values method: http://django.readthedocs.org/en/1.7.x/ref/models/querysets.html#django.db.models.query.QuerySet.values. It will produce dict-like representation for objects fields you need.

Categories

Resources