hem.... just to point that out.... both javascript and python don't provide
a method for standard dicts to be serialized with some predefined order in
respect of the keys.
There are ways to "display" the dict in an ordered matter BUT the object
itself, being a dictionary, has no notion of "display the values in this
order". So, it's purely a matter of representation.
tl;dr : there is no way in hell that the object would be evaluated
differently if the items are in sparse order
If you need it to be ordered always with the same order to do binary
comparison, with simplejson shipped with web2py, you can pass
simplejson.dumps(object,sort_keys=True) to get the dict ordered by keys.
You're unlucky, Records comes first than Result in natural ordering.
You need to install an updated simplejson version and import that over
web2py's default (import simplejson vs from gluon.contrib import
simplejson) and poke with OrderedDict. python 2.7 has a
collections.OrderedDict that "remebers" the order of insertion of keys. For
not so recent pythons, recent simplejson distributions come with a drop-in
replacement
>>> from simplejson import OrderedDict, dumps
>>> mydict = OrderedDict(Result='OK', Records=['a','b'])
>>> dumps(mydict)
'{"Records": ["a", "b"], "Result": "OK"}'
##keys were inserted in the same sentence, no order preserved
>>> mydict2 = OrderedDict(Result='OK')
>>> mydict2['Records']=['a','b']
>>> dumps(mydict2)
'{"Result": "OK", "Records": ["a", "b"]}'
On Thursday, August 2, 2012 7:57:25 PM UTC+2, Derek wrote:
>
> Exactly, They are unordered, and if you need it ordered, you should
> specify an order for it. However, you should not need it ordered a
> particular way.
>
> On Thursday, August 2, 2012 7:09:31 AM UTC-7, Jonathan Lundell wrote:
>>
>> On 2 Aug 2012, at 1:43 AM, Hassan Alnatour <[email protected]>
>> wrote:
>>
>> i want to Generate json like this one :
>>
>> {
>> "Result":"OK",
>> "Records":[
>> {"PersonId":1,"Name":"Benjamin
>> Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
>> {"PersonId":2,"Name":"Douglas
>> Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
>> {"PersonId":3,"Name":"Isaac
>> Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
>> {"PersonId":4,"Name":"Thomas
>> More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
>> ]
>> }
>>
>> so i did this :
>>
>> def person():
>>
>> data = db().select(db.Person.ALL)
>>
>> mylist = {}
>>
>> mylist['Result'] = 'OK'
>> for i in data:
>> i.name = {'name':i.name,'age':i.age}
>> mylist['Records'].append(i.name)
>> return mylist
>>
>>
>> then i open person.json , but i keep getting the order like this :
>>
>>
>> {"Records": [{"age": "222", "name": "hassan"}, {"age": "23", "name":
>> "mazen"}], "Result": "OK"}
>>
>>
>> but i want the 'Result' : 'ok' to be at the beginning , what can i do ?
>>
>>
>> Python dictionaries (and I assume JavaScript objects as well) are
>> unordered. Why do you care?
>>
>
--