python json
Python hosting: Host, run, and code Python in the cloud!
Introduction
JSON (JavaScript Object Notation) is frequently used between a server and a web application. An example of JSON data:
{ |
The json module enables you to convert between JSON and Python Objects.
Related course:
Data Analysis with Python Pandas
JSON conversion examples
Convert JSON to Python Object (Dict)
To convert JSON to a Python dict use this:
import json |
Convert JSON to Python Object (List)
JSON data can be directly mapped to a Python list.
import json |
Convert JSON to Python Object (float)
Floating points can be mapped using the decimal library.
import json |
Convert JSON to Python Object (Example)
JSON data often holds multiple objects, an example of how to use that below:
import json |
Convert Python Object (Dict) to JSON
If you want to convert a Python Object to JSON use the json.dumps() method.
import json |
Converting JSON data to Python objects
JSON data can be converted (deserialized) to Pyhon objects using the json.loads() function. A table of the mapping:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
Pretty printing
If you want to display JSON data you can use the json.dumps() function.
import json |
Leave a Reply:
Warning: do not name your test file json.py (it's tempting for some reason). In general, don't name your source the same as pre-defined imported modules. The import looks in the local directory first.
Correct, you cannot name your file json.py because we import json. This is the general case in python and can be confusing. Thanks for your comment