Python and JSON
The main things to know when working with JSON are:
- import with
import json
json.dumps(arg)
will return a JSON string based on argjson.dumps
will accept:- lists
- tuples
- dictionaries
json.dumps
will not accept- sets
- ranges
json.loads(stringArg)
can be used to convert a JSON string to a python object.- lists and tuples encode to JSON arrays, but always decode back to lists.
- JSON objects convert back to dictionaries.
json.dumps
does not accept sets and ranges, you can work around this by converting them to lists as shown below.
Encoding Demo
Below is a demo of outputting various types to JSON.
import json
# List example
myList = ['a', 'b', 'c']
myListAsString = json.dumps(myList)
print(myListAsString) # prints ["a", "b", "c"]
# Tuple example
myTuple = ('a', 'b', 'c')
myTupleAsString = json.dumps(myTuple)
print(myTupleAsString) # prints ["a", "b", "c"]
# Dictionary example
myDict = {'jack': 4098, 'sape': 4139}
myDictAsString = json.dumps(myDict)
print(myDictAsString) # prints {"jack": 4098, "sape": 4139}
# Range example
myRange = range(1,10,1)
myRangeAsList = list(myRange) # convert to list for json
myRangeAsString = json.dumps(myRangeAsList)
print(myRangeAsString)
# Set Example
mySet = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
mySetAsList = list(myRange) # convert to list for json
mySetAsString = json.dumps(mySetAsList)
print(mySetAsString)
Decoding Demo
import json
myJsonString = '["a", "b", "c"]'
myObj = json.loads(myJsonString)
print(myObj) # prints the list ['a', 'b', 'c']
myJsonString = '{ "myArray" : ["a", "b", "c"] }'
myObj = json.loads(myJsonString)
print(myObj) # prints {'myArray': ['a', 'b', 'c']}
Conclusion
We have covered the basics with working with JSON in Python. There are more methods that the json library provides which you can read about here.
Last updated: 25th March 2021
First published: 16th August 2018
First published: 16th August 2018