From the course: Effective Serialization with Python

Basic JSON serialization

- Say, you'd like to automate your pup. You want to send an event every time there is a purchase. Here is what an event might look like. We have a shopping event, which is a python dict. Note that in Json, you can see also other types, such as numbers, strings, or lists. In our event, we have the customer name, we have the item they bought, we have the amount, and finally we have the item price. Let's see how we can walk with Json. So, Ipython and from event, we import the event and we're going to import the json library. The json library has dump S and load S for working with strings. So data is json.dumps of our event. And the type of data is a str. Sometimes when you want to pass the data to a socket, you will need to convert it to a bytes. So, data_bytes, equal data.encode utf-8, and then the type of data_bytes, is bytes. If you look at the data, we see that it's one long line. Sometimes we'd like to see the data in the dicey. You can use the indent parameter to do that. Print json.dumps of event and we say that the intent equal four. If you already have a data in one long line in a file, there are other tools you can use to make it pretty. These tools are either python-m json.tools that comes with python, or a tool called jq, which you can install externally. So if you want to decentralize so event str it equal json, this time we're going through the load S and we're going to take it from the data. And we can see that event str equals to the original event. If you want to walk with files, we are going to use the load and dump without the S. So, with open event.json, and we're going to open the file for writing is out. You're going through the json.dump our event, to the file. And now the event is stored as json in the file. If you want to load the data from the file again with open, event.json as fp and we're going to say that event that came from the file equal json.load of the file. And again, event.file equal event receive, you got the same data.

Contents