Python provides built-in JSON libraries to encode and decode JSON.
In Python 2.5, the simplejson module is used, whereas in Python 2.7, the json module is used. Since this interpreter uses Python 2.5, we'll be using simplejson.
In order to use the simplejson module, it must first be imported:
import simplejson
To encode a data structure to JSON, use the "dumps" method:
json_string = simplejson.dumps([1, 2, 3, "a", "b", "c"])
To load JSON back to a data structure, use the "loads" method:
print simplejson.loads(json_string)
Python supports a Python proprietary data serialization method called pickle (and a faster alternative called cPickle).
You can use it exactly the same way.
import cPickle
pickled_string = cPickle.dumps([1, 2, 3, "a", "b", "c"])
print cPickle.loads(pickled_string)
The aim of this exercise is to print out the JSON string with key-value pair "Me" : 800 added to it.
def add_employee(jsonSalaries, name, salary): #Exercise fix this function, so it adds the given name and salary pair to the json it returns return jsonSalaries
originalJsonSalaries = '{"Alfred" : 300, "Jane" : 301 }' newJsonSalaries = add_employee(originalJsonSalaries, "Me", 800) print(newJsonSalaries)
{"Jane": 301, "Me": 800, "Alfred": 300}