Learning Python Network Programming

(Sean Pound) #1
Chapter 3

Also, it is useful to know how JSON handles nested objects.





d = {





... 'Chapman': ['King Arthur', 'Brian'],


... 'Cleese': ['Sir Lancelot', 'The Black Knight'],


... 'Idle': ['Sir Robin', 'Loretta'],


... }





json.dumps(d)





'{"Chapman": ["King Arthur", "Brian"], "Idle": ["Sir
Robin", "Loretta"], "Cleese": ["Sir Lancelot", "The Black
Knight"]}'


There is just one gotcha though: JSON dictionary keys can only be in the form
of strings.





json.dumps({1:10, 2:20, 3:30})





'{"1": 10, "2": 20, "3": 30}'


Notice, how the keys in the JSON dictionary become string representations of
integers? To decode a JSON dictionary that uses numeric keys, we need to manually
type-convert them if we want to work with them as numbers. Do the following to
accomplish this:





j = json.dumps({1:10, 2:20, 3:30})








d_raw = json.loads(j)








d_raw





{'1': 10, '2': 20, '3': 30}





{int(key):val for key,val in d_raw.items()}





{1: 10, 2: 20, 3: 30}


We just use a dictionary comprehension to apply int() to the dictionary's keys.


Other object types


JSON cleanly handles only Python lists and dicts, for other object types json may
attempt to cast the object type as one or the other, or fail completely. Try a tuple,
as shown here:





json.dumps(('a', 'b', 'c'))





'["a", "b", "c"]'

Free download pdf