XML is good at representing things that may have elements nested within elements, like documents.
JSON is not so great at representing documents, but it is very good at representing many other types of data.
my_list = [‘item1’, ‘item2’, ‘item3’]
JSON was defined by Douglas Crockford. Once he published it, people quickly started using it. JSON is now an entire industry within itself. Its pure organic growth is a testament to its usefulness.
JSON has two basic structures. They are an array and an object. It’s best advantage is that in Python you tend to make lists and dictionaries. JSON is a great way to represent those.
Look at the picture of some JSON below. It may seem familiar to you.
- The data represents an object inside the triple quote syntax (which technically makes it a string).
- After the first curly bracket, you have key / value pair followed by a comma.
- The first key / value pair is “name” : “Chuck”.
- In the second key / value pair, the value is a whole other object.
- The key is “phone”, and its value is another object with two key / value pairs.
If you look at the whole outer thing, there are three keys: “name”, “phone”, and “email”.
This is the basic information about how you structure data, but the main thing you need to think about is how to de-serialize the data.
Like many other thinks, JSON is built-in to Python. This is why you start your code with:
The next step is to de-serialize from string to internal Python data structure.
info = json.loads(data)
The method “loads” is saying load from string, and data is the string that you are passing in as the parameter.
The really nice part is that “info” is returned as an actual Python dictionary. You pull information out of this dictionary the same as you would any other native Python dictionary. Thus, running this code will result in the following:
JSON Representation of an Array
The array “input” starts with square brackets. This is the same as a list in Python. In this case, “input” is an array of two objects. The objects are inside curly brackets, and separated by a comma.
Examine the following declaration:
info = json.loads(input)
As you could maybe guessed, this will return a native Python list. As with any list, you can use a “for” loop to iterate through the list items.
Running this program should result in what you would expect.