Lets start with an example: https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json
Source: http://stackoverflow.com/questions/4310315/what-exactly-is-json
Follow the beginning of this tutorial: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
-
Validate JSON by pasting into this tool (or many other "linters") online. They will display the data properly and tell you if its valid JSON or not. If it is not valid, you might have trouble reading it into a programming language.
-
JSON Formatter Chrome Extension: https://chrome.google.com/webstore/detail/json-formatter/mhimpmpmffogbmmkmajibklelopddmjf
Similar to the JSON format, Python has the concept of dicts
. While JSON can be entirely represented by a string as it is used for transfering data, a python dict
can use native datatypes like integers, floats, datetimes, etc.
As a quick reminder, a dict
is made up of key
s (left side of the colon) and value
s (right side of the colon): {k: v}
.
Here is the same example from before as a dict:
{'active': True,
'formed': 2016,
'homeTown': 'Metro City',
'members': [{'age': 29,
'name': 'Molecule Man',
'powers': ['Radiation resistance',
'Turning tiny',
'Radiation blast'],
'secretIdentity': 'Dan Jukes'},
{'age': 39,
'name': 'Madame Uppercut',
'powers': ['Million tonne punch',
'Damage resistance',
'Superhuman reflexes'],
'secretIdentity': 'Jane Wilson'},
{'age': 1000000,
'name': 'Eternal Flame',
'powers': ['Immortality',
'Heat Immunity',
'Inferno',
'Teleportation',
'Interdimensional travel'],
'secretIdentity': 'Unknown'}],
'secretBase': 'Super tower',
'squadName': 'Super hero squad'}
Notice how it is almost identical to the superheroes JSON we saw earlier. Some differences are a python dict can be written using single or double quotes and unlike Javascript, both the "keys" and "values" don't have to be strings, they can be almost any datatype. In addition, we can see that the dict
above is using native python datatypes as the boolean value True
has a capital T unlike the original json.
We can also see that the JSON above has a list
embedded inside of it for the list of members
. This is written in python exactly the same way.
We can use the mydict[key]
syntax to access and change dicts.
mydict = {
'a': 1,
'b': 2,
'c': 3
}
mydict['d'] = 4
print(mydict)
print(mydict['c'])
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
3
The example above, adds a single key to a dict where the key is d
and the value is 4
. We then print mydict['c']
which gives us 3.
# This example starts with a list, `mylist` and prints out the first element of the list. Note that lists in python are 0-indexed. The first element of the list is `1`.
mylist = [1, 2, 3]
print(mylist[0])
# Then, we append `4` to the end of the list and print the whole thing out. We can see the list now has 4 elements.
mylist.append(4)
print(mylist)
# Last, we print out the element with index 2 (i.e. the 3rd element of the list which is 3).
print(mylist[2])
Output:
1
[1, 2, 3, 4]
3