Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Reading and Writing JSON to a File in Python
Next article icon

JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON.

Example of JSON String

s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}'

The syntax of JSON is considered a subset of the syntax ofJavaScript including the following:

  • Name/Value pairs:Represents Data, the name is followed by a colon(:), and the Name/Value pairs are separated by a comma(,).
  • Curly braces: Holds objects.
  • Square brackets: Hold arrays with values separated by a comma (,).

Keys/Name must be strings with double quotes and values must be data types amongst the following: 

Example of JSON file:

 {
"employee": [
{
"id": "01",
"name": "Amit",
"department": "Sales"
},
{
"id": "04",
"name": "sunil",
"department": "HR"
}
]
}

Python Parse JSON String

In the below code, we are going to convert JSON to a Python object. To parse JSON string Python firstly we import the JSON module. We have a JSON string stored in a variable 'employee' and we convert this JSON string to a Python object usingjson.loads()method of JSON module in Python. After that, we print the name of an employee using the key 'name'.

Python3
# Python program to convert JSON to Pythonimportjson# JSON stringemployee='{"id":"09", "name": "Nitin", "department":"Finance"}'# Convert string to Python dictemployee_dict=json.loads(employee)print(employee_dict)print(employee_dict['name'])

Output
{'id': '09', 'name': 'Nitin', 'department': 'Finance'}Nitin

Python read JSON file

Let's suppose we have a JSON file that looks like this.

pyhton-append-json1


Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data.

Python3
importjson# Opening JSON filef=open('data.json',)# returns JSON object as# a dictionarydata=json.load(f)# Iterating through the json# listforiindata['emp_details']:print(i)# Closing filef.close()

Output:

python-read-json-output1

Convert Python Dict to JSON

In the below code, we are converting a Python dictionaryto a JSON object using json.dumps() method of JSON module in Python. We first import the JSON module and then make a small dictionary with some key-value pairs and then passed it into json.dumps() method with 'indent=4' to convert this Python dictionary into a JSON object. As we have given the value of indent to 4 there are four whitespaces before each data as seen in the output.

Python3
# Python program to convert# Python to JSONimportjson# Data to be writtendictionary={"id":"04","name":"sunil","department":"HR"}# Serializing jsonjson_object=json.dumps(dictionary,indent=4)print(json_object)

Output
{    "id": "04",    "name": "sunil",    "department": "HR"}

The following types of Python objects can be converted into JSON strings: 

Python objects and their equivalent conversion to JSON:

Python

JSON Equivalent

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

Writing JSON to a file in Python

We can write JSON to file using json.dump() function of JSON module and file handling in Python. In the below program, we have opened a file named sample.json in writing mode using'w'. The file will be created if it does not exist. Json.dump() will transform the Python dictionary to a JSON string and it will be saved in the file sample.json.

Python3
# Python program to write JSON# to a fileimportjson# Data to be writtendictionary={"name":"sathiyajith","rollno":56,"cgpa":8.6,"phonenumber":"9976770500"}withopen("sample.json","w")asoutfile:json.dump(dictionary,outfile)

Output:

python-json-write-to-file

Python Pretty Print JSON

When we convert a string to JSON the data is in a less readable format. To make it more readable we can use pretty printing by passing additional arguments in json.dumps() function such asindent and sort_keys as used in the below code.

Python3
# Python program to convert JSON to Pythonimportjson# JSON stringemployee='{"id":"09", "name": "Nitin", "department":"Finance"}'# Convert string to Python dictemployee_dict=json.loads(employee)# Pretty Printing JSON string backprint(json.dumps(employee_dict,indent=4,sort_keys=True))

Output
{    "department": "Finance",    "id": "09",    "name": "Nitin"}

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp