simplejson

How to make simplejson serializable class

醉酒当歌 提交于 2019-11-29 09:32:32
问题 I have a class defined like this class A: def __init__(self): self.item1 = None def __repr__(self): return str(self.__dict__) when I do: >>> import simplejson >>> myA = A() >>> simplejson.dumps(myA) TypeError: {'item1': None} is not JSON serializable I can't find the reason why. Do I need to add any particular method to A for simplejson to serialize my class object? 回答1: You can't serialize arbitrary objects with simplejson . You need to pass a default and object_hook to dump and load . Here

Decode json and Iterate through items in django template

天涯浪子 提交于 2019-11-29 09:24:07
问题 Hi I am using simplejson to import some json and then decode for use within a django template, this is the decoded json: {u'ServerID': 1, u'Cache': {u'CacheBusted': False, u'FromCache': True}, u'Result': [{u'Url': u'http://listen.grooveshark.com/playlist/Soul_Power/399134', u'Cache': {u'FromCache': True}, u'PlaylistID': u'399134', u'Name': u'Soul Power', u'ModifiedTime': u'1229427645'}, {u'Url': u'http://listen.grooveshark.com/playlist/4RK_(v.3)/491934', u'Cache': {u'FromCache': True}, u

Check whether the JSON (object property exists) & print it as unicode decoded

瘦欲@ 提交于 2019-11-29 02:55:50
问题 I get the following data from the Instagram API, I m trying to get the text property from the caption using the following code: data = simplejson.load(info) # info is retrieved using the urllib2 for post in data['data']: if post['caption'] is not "null": try: post['caption']['text'] except NameError: post['caption']['text'] = 0 if post['caption']['text'] is not 0: print post['caption']['text'] But I keep getting the TypeError: 'NoneType' object has no attribute '__getitem__' error +

Python JSON encoding

北城余情 提交于 2019-11-28 16:19:31
I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. Currently I am declaring a list, looping through and another list, and appending one list within another: import simplejson, json data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']] x = simplejson.loads(data) # >>> typeError: expected string or buffer.. x = simplejson.dumps(stream) # >>> [["apple", "cat"], [

Can't parse simple json with python

不打扰是莪最后的温柔 提交于 2019-11-28 10:33:13
I have a very simple json I can't parse with simplejson module. Reproduction: import simplejson as json json.loads(r'{"translatedatt1":"Vari\351es"}') Result: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.5/simplejson/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib/pymodules/python2.5/simplejson/decoder.py", line 335, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/pymodules/python2.5/simplejson/decoder.py", line 351, in raw_decode obj, end = self.scan_once(s, idx) ValueError:

Json dumping a dict throws TypeError: keys must be a string

Deadly 提交于 2019-11-28 08:25:15
I m trying to convert the following dict into JSON using json.dumps : { 'post_engaged': 36, 'post_impressions': 491, 'post_story': 23, 'comment_count': 6, 'created_time': '03:02 AM, Sep 30, 2012', 'message': 'Specialities of Shaktis and Pandavas. \n While having power, why there isn\\u2019t', < built - in function id > : '471662059541196', 'status_type': 'status', 'likes_count': 22 } { 'post_engaged': 24, 'text': '30 Sept 2012 Avyakt Murlli ( Dual Voice )', 'post_story': 8, 'comment_count': 3, 'link': 'http:\\/\\/www.youtube.com\\/watch?v=VGmFj8g7JFA&feature=youtube_gdata_player', 'post

jQuery.getJSON doesn't trigger callback

*爱你&永不变心* 提交于 2019-11-28 06:49:39
I have a html code: <button>asd</button> <script type = "text/javascript"> $('button').click( function() { $.getJSON('/schedule/test/', function(json) { alert('json: ' + json + ' ...'); }); } ); </script> and corresponding view: def test(request): if request.method == 'GET': json = simplejson.dumps('hello world!') return HttpResponse(json, mimetype = 'application/json') The view is executed (tested using print ), json variable is initialised but no alert appears. What did I do wrong? I've already seen some docs on this ( http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback for example)

How to serialize db.Model objects to json?

点点圈 提交于 2019-11-28 05:26:43
When using from django.utils import simplejson on objects of types that derive from db.Model it throws exceptions. How to circumvent this? spidee Ok - my python not great so any help would be appreciated - You dont need to write a parser - this is the solution: add this utlity class http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55 import datetime import time from google.appengine.api import users from google.appengine.ext import db #this is a mod on the orinal file for some reason it includes its own simplejson files i have ref django! from django

Easiest way to serialize a simple class object with simplejson?

断了今生、忘了曾经 提交于 2019-11-28 03:41:52
I'm trying to serialize a list of python objects with JSON (using simplejson) and am getting the error that the object "is not JSON serializable". The class is a simple class having fields that are only integers, strings, and floats, and inherits similar fields from one parent superclass, e.g.: class ParentClass: def __init__(self, foo): self.foo = foo class ChildClass(ParentClass): def __init__(self, foo, bar): ParentClass.__init__(self, foo) self.bar = bar bar1 = ChildClass(my_foo, my_bar) bar2 = ChildClass(my_foo, my_bar) my_list_of_objects = [bar1, bar2] simplejson.dump(my_list_of_objects,

Install python packages on OpenShift

℡╲_俬逩灬. 提交于 2019-11-28 01:14:30
I'm trying to install python packages on OpenShift but I see a dearth of pages about the best way to do this. Can someone please suggest the best way of getting on say oauth2 and simplejson . I've tried including these in the setup.py , but I have no idea whether these are actually available or I'll have to upload and point to the path. How can I do this? Did you install rhc (made by OpenShift.com) ? If not then see on OpenShift.com: Installing OpenShift RHC Client Tools Now you can access server with rhc rhc ssh and then you can do as always: checking python version (with big V) python -V