
Here is an example of how you can create JSON.
#!/usr/bin/python
import json
raw_json = '{"foo": "Hello", "bar": "World"}'
print(raw_json)
Which should print the following.
{"foo": "Hello", "bar": "World"}
json.loads can be used to parse the JSON.
#!/usr/bin/python3
import json
raw_json = '{"foo": "Hello", "bar": "World"}'
try:
parsed_json = json.loads(raw_json)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(parsed_json)
Which should return the following.
{u'foo': u'Hello', u'bar': u'World'}
And here is how you can print the value of a certain key. This should print Hello in this example.
#!/usr/bin/python3
import json
raw_json = '{"foo": "Hello", "bar": "World"}'
try:
parsed_json = json.loads(raw_json)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(parsed_json['foo'])
Let's say you reference a key that does not exist in the dictionary.
#!/usr/bin/python3
import json
raw_json = '{"foo": "Hello", "bar": "World"}'
try:
parsed_json = json.loads(raw_json)
except Exception as exception:
print(f"Got the following exception: {exception}")
print(parsed_json['bogus'])
This should raise a KeyError.
Traceback (most recent call last):
File "example.py", line 6, in <module>
print(parsed_json['bogus'])
KeyError: 'bogus'
try except else can be used to handle KeyError.
#!/usr/bin/python
import json
raw_json = '{"foo": "Hello", "bar": "World"}'
parsed_json = json.loads(raw_json)
try:
parsed_json['bogus']
except KeyError:
print("JSON does not contain key 'bogus'")
else:
print(parsed_json['bogus'])
It's important to recognize that a dictionary is very similar to JSON, but not exactly the same.
#!/usr/bin/python
import json
dictionary = {"foo": "Hello", "bar": "World"}
raw_json = '{"foo": "Hello", "bar": "World"}'
print(type(dictionary))
print(dictionary)
print(type(raw_json))
print(raw_json)
Which should print the following, which shows that the dictionary type is dict whereas the JSON is actually a string, which can be seen by the fact that the JSON is wrapped in single quotes so that it's a string.
<type 'dict'>
{'foo': 'Hello', 'bar': 'World'}
<type 'str'>
{"foo": "Hello", "bar": "World"}
Did you find this article helpful?
If so, consider buying me a coffee over at