Movatterモバイル変換


[0]ホーム

URL:


Open In App

Thejson module in Python provides an easy way to convert JSON data into Python objects. It enables the parsing of JSON strings or files into Python's data structures like dictionaries. This is helpful when you need to process JSON data, which is commonly used in APIs, web applications, and configuration files.

Python JSON to Dictionary

json.loads()function parses a JSON string into a Python dictionary.

parsejson1
Parse JSON
Python
importjsongeek='{"Name": "nightfury1", "Languages": ["Python", "C++", "PHP"]}'geek_dict=json.loads(geek)# Displaying dictionaryprint("Dictionary after parsing:",geek_dict)print("\nValues in Languages:",geek_dict['Languages'])

Output:

Dictionary after parsing:  {'Name': 'nightfury1', 'Languages': ['Python', 'C++', 'PHP']}

Values in Languages:  ['Python', 'C++', 'PHP']

Python JSON to Ordered Dictionary

To parse JSON objects into an ordered dictionary, use the json.loads() function withobject_pairs_hook=OrderedDictfrom the collections module.

Python
importjsonfromcollectionsimportOrderedDictdata=json.loads('{"GeeksforGeeks":1, "Gulshan": 2, "nightfury_1": 3, "Geek": 4}',object_pairs_hook=OrderedDict)print("Ordered Dictionary: ",data)

Output:

Ordered Dictionary:  OrderedDict([('GeeksforGeeks', 1), ('Gulshan', 2), ('nightfury_1', 3), ('Geek', 4)])

Parse using JSON file

json.load() method parses a JSON file into a Python dictionary. This is particularly useful when the data is stored in a .json file.

parsejson2
Parsing JSON File
Python
importjsonwithopen('data.json')asf:data=json.load(f)# printing data from json fileprint(data)

Output:

{'Name': 'nightfury1', 'Language': ['Python', 'C++', 'PHP']}


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