Movatterモバイル変換


[0]ホーム

URL:


Open In App

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:

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

JSON Syntax

The syntax of JSONis a subset ofJavaScript's objectnotation and includes the following structural rules:

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

Example JSON file

{
"employee": [
{
"id": "1",
"name": "Amit",
"department": "Sales"
},
{
"id": "4",
"name": "Sunil",
"department": "HR"
}
]
}

Parsing JSON in Python

To convert a JSON string into a Python dictionary, use the json.loads() method from Python’s built-in json module.

Python
importjsonemp='{"id": "9", "name": "Nitin", "dept": "Finance"}'emp_dict=json.loads(emp)print(emp_dict)print(emp_dict['name'])

Output
{'id': '9', 'name': 'Nitin', 'dept': 'Finance'}Nitin

Reading JSON from File

If you have JSON data stored in a .json file (for example, downloaded from an API or stored locally), Python's json module makes it easy to read and convert it into a Python dictionary using the json.load() function.

Assume the file data.json contains:

python-append-json1

Example:

Python
importjsonf=open('data.json',)data=json.load(f)foriindata['emp_details']:print(i)f.close()

Output:

python-read-json-output1

Convert Python Dictionary to JSON String

Python dictionaries can be easily converted to JSON strings using json.dumps(). This is useful when you want to send data over the network or store it in a text-based format.

Python
importjsonemp={"id":"4","name":"Sunil","department":"HR"}json_obj=json.dumps(emp,indent=4)print(json_obj)

Output
{    "id": "4",    "name": "Sunil",    "department": "HR"}

Python to JSON Data Type Conversion

Here's how Python's native types are converted to JSON equivalents:

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

Use json.dump() to write a Python dictionary to a JSON file. This is helpful for saving configuration, logs, user data or processed results.

Python
importjsondata={"name":"Sathiyajith","rollno":56,"cgpa":8.6,"phonenumber":"9976770500"}withopen("sample.json","w")asoutfile:json.dump(data,outfile)

Output

python-json-write-to-file

Python Pretty Print JSON

When JSON is returned as a single line, it’s hard to read. You can pretty print JSON with indentation and sorted keys using thejson.dumps() function.

Example:

Python
importjsonemp='{"id":"9", "name": "Nitin", "department":"Finance"}'emp_d=json.loads(emp)print(json.dumps(emp_d,indent=4,sort_keys=True))

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

Improve
Improve
Article Tags :

Explore

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