Custom Search

Sunday, March 13, 2011

python json examples

python json examples

import json

#list
list_str = '[1,2,3]'

#dict
#dict_str = "{'a':1, 'b':5}" #Not works (do not use single quote inside)
dict_str = '{"a":1, "b":5}'


#tuple
#json does not support typles
tup = (5,6,7,8)
tup_str = json.dumps(tup)
print "\n-------tup_strdd----", tup_str

#dict_list_str = "{'l1':[2,4], 'l2':[6,7], 'd1':{'x':8, 'y':3}, 'name':'my_name'}"
dict_list_str = '{"l1":[2,4], "l2":[6,7], "d1":{"x":8, "y":3}, "name":"my_name"}'


print "\n-------json.loads(list_str)-------", json.loads(list_str)

print "\n-------json.loads(dict_str)-------", json.loads(dict_str)

print "\n-------json.loads(tup_str)-------", json.loads(tup_str)

print "\n-------json.loads(dict_list_str)-------", json.loads(dict_list_str)


OUTPUT
=======
-------tup_strdd---- [5, 6, 7, 8]

-------json.loads(list_str)------- [1, 2, 3]

-------json.loads(dict_str)------- {u'a': 1, u'b': 5}

-------json.loads(tup_str)------- [5, 6, 7, 8]

-------json.loads(dict_list_str)------- {u'd1': {u'y': 3, u'x': 8}, u'l2': [6, 7],
u'name': u'my_name', u'l1': [2, 4]}


============ Notes =========

#http://diveintopython3.org/serializing.html
#http://diveintopython3.org/serializing.html#json-dump
#http://diveintopython3.org/serializing.html#json-types

Json Types
------------
* http://diveintopython3.org/serializing.html#json-types
* JSON does not support Python Tuples & bytes
* JSON has an array type, which the json module maps to a Python list.

No comments:

Post a Comment