EzDevInfo.com

simplejson

simplejson is a simple, fast, extensible JSON encoder/decoder for Python simplejson — JSON encoder and decoder — simplejson 3.8.0 documentation

How to make simplejson serializable class

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?


Source: (StackOverflow)

Using Python simplejson to return pregenerated json

I have a GeoDjango model object that I want't to serialize to json. I do this in my view:

lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
a = Authority.objects.get(area__contains=Point(lng, lat))
if a:
    return HttpResponse(simplejson.dumps({'name': a.name, 
                                          'area': a.area.geojson,
                                          'id': a.id}), 
                        mimetype='application/json')

The problem is that simplejson considers the a.area.geojson as a simple string, even though it is beautiful pre-generated json. This is easily fixed in the client by eval()'ing the area-string, but I would like to do it proper. Can I tell simplejson that a particular string is already json and should be used as-is (and not returned as a simple string)? Or is there another workaround?

UPDATE Just to clarify, this is the json currently returned:

{
    "id": 95,
    "name": "Roskilde",
    "area": "{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.078701, 55.649927 ], ... ] ] ] }"
}

The challenge is to have "area" be a json dictionary instead of a simple string.


Source: (StackOverflow)

Advertisements

Google Data Source JSON not valid?

I am implementing a Google Data Source using their Python Library. I would like the response from the library to be able to be imported in another Python script using the simplejson library.

However, even their example doesn't validate in JSONLint:

{cols: 
    [{id:'name',label:'Name',type:'string'},
     {id:'salary',label:'Salary',type:'number'},
     {id:'full_time',label:'Full Time Employee',type:'boolean'}],
rows: 
    [{c:[{v:'Jim'},{v:800,f:'$800'},{v:false}]},
     {c:[{v:'Bob'},{v:7000,f:'$7,000'},{v:true}]},
     {c:[{v:'Mike'},{v:10000,f:'$10,000'},{v:true}]},
     {c:[{v:'Alice'},{v:12500,f:'$12,500'},{v:true}]}]}

How do I tweak the simplejson 'loads' function to import the above JSON? I think the main problem is that the object keys are not strings.

I would rather not write a regex to convert the keys to strings since I think such code would be annoying to maintain.

I am currently getting an "Expecting property name: line 1 column 1 (char 1)" error when trying to import the above json into python with simplejson.


Source: (StackOverflow)

simplejson.loads() get Invalid \escape: 'x'

I am learning how to use simplejson to decode JSON file. But I suffered the "invalid \escape" error. Here is the code

import simplejson as json

def main():
    json.loads(r'{"test":"\x27"}')

if __name__ == '__main__':
    main()

And here is the error message

Traceback (most recent call last):
  File "hello_world.py", line 7, in <module>
    main()
  File "hello_world.py", line 4, in main
    json.loads(r'{"test":"\x27"}')
  File "C:\Users\zhangkai\python\simplejson\__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "C:\Users\zhangkai\python\simplejson\decoder.py", line 335, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\zhangkai\python\simplejson\decoder.py", line 351, in raw_decode

    obj, end = self.scan_once(s, idx)
  File "C:\Users\zhangkai\python\simplejson\scanner.py", line 36, in _scan_once
    return parse_object((string, idx + 1), encoding, strict, _scan_once, object_
hook)
  File "C:\Users\zhangkai\python\simplejson\decoder.py", line 185, in JSONObject

    value, end = scan_once(s, end)
  File "C:\Users\zhangkai\python\simplejson\scanner.py", line 34, in _scan_once
    return parse_string(string, idx + 1, encoding, strict)
  File "C:\Users\zhangkai\python\simplejson\decoder.py", line 114, in py_scanstr
ing
    raise ValueError(errmsg(msg, s, end))
ValueError: Invalid \escape: 'x': line 1 column 10 (char 10)

I think json parser is supposed to recognize the escape. So I want to know what is wrong, and what should I do.


Source: (StackOverflow)

How to serialize db.Model objects to json?

When using

from django.utils import simplejson

on objects of types that derive from db.Model it throws exceptions. How to circumvent this?


Source: (StackOverflow)

Decode complex JSON in Python

Hey, I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:

php > $insidejson = array('foo' => 'bar','foo1' => 'bar1');
php > $arr = array('a' => array('a1'=>json_encode($insidejson)));
php > echo json_encode($arr);
{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}

Then, with Python, I try deocding it using simplejson:

>>> import simplejson as json
>>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}')

This fails with the following error:

Traceback (most recent call last):
  File "", line 1, in ?
  File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads
  File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode
  File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode
ValueError: Expecting , delimiter: line 1 column 14 (char 14)

How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.

Thanks!


Source: (StackOverflow)

How to solve the ImportError: cannot import name simplejson in Django

I'm trying to build a realtime chat app in Django(1.7.1). It seems that I needed to install Redis and ishout.js. So I installed them by following the instructions.

After making the project in Django, I put 'drealtime' under the INSTALLED_APPS, and put:

'drealtime.middleware.iShoutCookieMiddleware' 

right above :

'django.contrib.sessions.middleware.SessionMiddleware' 

under the MIDDLEWARE_CLASSES as it was saying. And I put the command like

python manage.py startapp example

but still I have this import error message:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 87, in create
    module = import_module(entry)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/drealtime/__init__.py", line 4, in <module>
    from django.utils import simplejson as json

After I searched through the Django official site, I found simplejson is no longer used and removed from new Django. I don't know why this is happening. Please give any feedback on this issue and possible remedy to tackle this issue.


Source: (StackOverflow)

Python: Convert simplejson dumped unicode datetime back to datetime object

I have...

entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())})

How do I convert the datetime (that was converted to unicode) back to datetime again?

So that I can do something like...

entity2 = simplejson.loads(entity)
#your answer here..
add5 = entity2["a"] + datetime.timedelta(minutes=5)

Thanks!


Source: (StackOverflow)

XML library similar to simplejson/json? - Python

is there a similar library to simplejson, which would enable quick serialization of data to and from XML.

e.g. json.loads('{vol:'III', title:'Magical Unicorn'}')

e.g. json.dumps([1,2,3,4,5])

Any ideas?


Source: (StackOverflow)

Is there any way to make simplejson less strict?

I'm interested in having simplejson.loads() successfully parse the following:

{foo:3}

It throws JSONDecodeError saying "expecting property name" but in reality it's saying "I require double quotes around my property names". This is annoying for my use case, and I'd prefer a less strict behavior. I've read the docs, but beyond making my own decoder class, I don't see anything obvious that changes this behavior.


Source: (StackOverflow)

Flask Jsonify mongoengine query

I have method like this , and want to return as Json , but it writes that Posts object is not Json serializable :S

def show_results_async(text):
   query  =  { '$or':[{'title':{'$regex':text}},{'author':{'$regex':text}} ]}
   posts = Posts.objects(__raw__=(query))
   return jsonify(result = posts)

Source: (StackOverflow)

Single versus double quotes in json loads in Python

I notice that single quotes cause simplejson's loads function to fail:

>>> import simplejson as json
>>> json.loads("\"foo\"")
'foo'
>>> json.loads("\'foo\'")
Traceback (most recent call last):
...
ValueError: No JSON object could be decoded

I'm parsing things like: foo = ["a", "b", "c"] from a textfile into lists in Python and would like to also accept foo = ['a', 'b', 'c']. simplejson is convenient for making foo automatically into a list.

How can I get loads to accept single quotes, or automatically substitute double for single quotes without wrecking the input? thanks.


Source: (StackOverflow)

installing simplejson on the google appengine

Super nub question time! I am trying to use simplejson on the google appengine. In a terminal on my machine I have simplejson installed and working. But my when I try to import it in a script running on the appengine I get an error saying no such library exists. If open the interactive console on my machine (from the link on http://localhost:8080/_ah/admin) and type "import simplejson" I get:

Traceback (most recent call last): File "/home/chris/google_appengine/google/appengine/ext/admin/init.py", line 210, in post exec(compiled_code, globals()) File "", line 1, in ImportError: No module named simplejson

Any thoughts?


Source: (StackOverflow)

How to ensure that a python dict keys are lowercase?

I have a dict that I want to convert in JSON using simplejson.

How can I ensure that all the keys of my dict are lowercase ?

    {
        "DISTANCE": 17.059918745802999, 
        "name": "Foo Bar", 
        "Restaurant": {
            "name": "Foo Bar", 
            "full_address": {
                "country": "France", 
                "street": "Foo Bar", 
                "zip_code": "68190", 
                "city": "UNGERSHEIM"
            }, 
            "phone": "+33.389624300", 
            "longitude": "7.3064454", 
            "latitude": "47.8769091", 
            "id": "538"
        }, 
        "price": "", 
        "composition": "", 
        "profils": {}, 
        "type_menu": "", 
        "ID": ""
    },

EDIT: Thanks all to had a look at my question, I am sorry I didn't explain in detailed why I wanted this. It was to patch the JSONEmitter of django-piston.


Source: (StackOverflow)

django escapejs and simplejson

I'm trying to encode a Python array into json using simplejson.dumps:

In [30]: s1 = ['test', '<script>']

In [31]: simplejson.dumps(s1)
Out[31]: '["test", "<script>"]'

Works fine.

But I want to escape the strings first (using escapejs from Django) before calling simplejson.dumps:

In [35]: s_esc
Out[35]: [u'test', u'\\u003Cscript\\u003E']

In [36]: print simplejson.dumps(s_esc)
["test", "\\u003Cscript\\u003E"]

My problem is: I want the escaped string to be: ["test", "\u003Cscript\u003E"] instead of ["test", "\\u003Cscript\\u003E"]

I can use replace:

In [37]: print simplejson.dumps(s_esc).replace('\\\\', '\\')
["test", "\u003Cscript\u003E"]

But is this a good approach? I just want to escape the strings first before encoding them to json. So there will be no syntax errors when I use them in template.

Thanks. :)


Source: (StackOverflow)