TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python json: Import JSON, load and dumps

Use the json module to convert Python lists into JSON lists. Specify other types like numbers.
Json. With JSON we can store data in an easy-to-parse format. We can encode JSON with Python, and then decode it in JavaScript with a single function call.
Improve compatibility. By using JSON we have fewer compatibility issues. We do not need to create special file formats (or we can store those formats inside JSON for simplicity).
Json.dumps. Python has built-in support for JSON. Consider this program. We import the json module and call its dumps() method. We have 2 Python lists we pass to dumps().

Tip: We can use regular Python objects like lists and dictionaries when creating JSON strings. Dumps returns a string containing JSON.

List
Python program that uses json module, dumps method import json # A list with a nested list. sublist = [10, 20, 30] list = ["cat", "frog", "fish", sublist] # Call dumps on our list. result = json.dumps(list) # Display the JSON data. print(result) print("Length:", len(result)) Output ["cat", "frog", "fish", [10, 20, 30]] Length: 37
Json.loads. With loads we can parse a JSON string and have Python objects like a list in our program. Loads() parses JSON. The JSON must be formatted correctly.
Python program that uses json.loads import json # A JSON string must use double-quotes. # ... We place the JSON data inside single-quotes here. result = json.loads('["bird", "frog", "fish", [10, 9, 8]]') # Print the resulting list. print(result) print("List length:", len(result)) # Get the sub list from the parsed JSON. sublist = result[3] print(sublist) print("Sublist length:", len(sublist)) Output ['bird', 'frog', 'fish', [10, 9, 8]] List length: 4 [10, 9, 8] Sublist length: 3
File load. With json.load we can read in JSON data from a file and parse it. Load() is different from the json.loads() method. It requires a file object.File

Here: We open the file important.data. We then pass the file object to json.load, which returns the Python list.

Python program that reads JSON from file on disk import json # Use open to get a file object for a JSON file. f = open(r"C:\programs\important.data", "r") # Use json.load to parse the data. result = json.load(f) # Print the resulting Python list. print(result) Contents: important.data ["important", "data", "file", [10, 20, 0]] Output ['important', 'data', 'file', [10, 20, 0]]
JSONDecodeError. JSON must be valid. It provides no recovery for invalid files. Here we try to decode an invalid JSON file (one with a string that is not terminated).

Result: The Python json module correctly throws an error. This is the JSONDecodeError.

Python program that causes json.decoder error import json # An error occurs when the JSON is invalid. result = json.loads('["invalid JSON data sorry') Output Traceback (most recent call last): ... json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 2 (char 1)
A summary. JSON is used for its extreme simplicity. It is compatible with all modern web browsers—no custom code is needed to handle JSON inside Chrome. This is a key advantage.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf