Loading...

Python JSON

JSON is text. A dict keeps names and values inside the program, but that dict is not JSON yet. dumps turns the dict into one line of text. This page does not open a file, and it does not build a path.

the dict becomes one line of text

python
import json
lamp = {"color": "blue", "watts": 7}
text = json.dumps(lamp)
print(text)

The screen shows {"color": "blue", "watts": 7}. color and blue sit inside double quotes. watts is a number, so 7 has no quotes. The space after each colon, and the space after the comma, belong to that same text. text is a string. No file is created. open and Path are not in this program.

the text becomes a dict again

python
import json
text = '{"color": "blue", "watts": 7}'
lamp = json.loads(text)
print(lamp["color"])
print(lamp["watts"])

The screen shows blue, then 7. loads reads the JSON text and builds the dict again. lamp["color"] is the word blue. The quotes stayed in the text; they are not part of the value. lamp["watts"] is the number 7, not the word 7. This program does not read a file. The text was already in the variable.

📊 dumps and loads

Call You start with You get back
json.dumps a dict one line of JSON text, and no file is written
json.loads JSON text a dict, and no file is read

If the text is not real JSON, loads stops. The name of that stop is JSONDecodeError. {color: blue} is not JSON, because the names and the word blue have no double quotes. That line is not in the programs on this page. None is not written in its place, and the program does not go on.

The next page is a CSV table. This page only turns a dict into text, and that text back into a dict.

Text, then the dict again

dumps shows {"color": "blue", "watts": 7}. loads then shows blue and 7. 7 is a number. A broken line stops as JSONDecodeError. No file is written or read. The next page is a CSV table.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top