If you work with web technologies these days, there is no way around JSON. Today we look at the basic operations to serialize our objects to JSON and turn JSON back into objects.
JSON in Python
JSON (JavaScript Object Notation) is a lightweight data interchange format. In Python we can use the built-in json module in a similar way to pickle. We do not need to install anything and can start with importing json in our code:
defexample():# You collect and combine data in an # arbitrarily nested data structure:data=[{'name':"Rebecca Stephenson",'phone':"(154) 221-8558",'zipCode':"900185",'country':"South Korea",'options':['a','b','c'],'total':"$74.79"},{'name':"Amos Nieves",'phone':"1-762-301-2264",'zipCode':"25566",'country':"Russian Federation",'options':{'a':'full','f':'partial','c':{'k1':1,'k2':3}},'total':"$21.78"}]returndata
We can create a JSON string with the dumps() method directly in-memory, without the need to write it to a file as we did with the similar method for pickle. I create a file only for the purpose of loading JSON in the next part:
Working with JSON in Python is surprisingly painless and you do not need to install anything. All you need is a method call and your objects are in the JSON format.