Movatterモバイル変換


[0]ホーム

URL:


Finally, a Python course that's visual, but not video.
Finally, a Python course that's visual, but not video.
Try it yourself!
Sale ends in
Finally, a Python course that's visual, but not video.
Finally, a Python course that's visual, but not video.
Try it yourself!
Sale ends in

Become a certified Python
programmer.

ENROLL

Python JSON

JSON (JavaScriptObjectNotation) is a popular data format used for representing structured data. It's common to transmit and receive data between a server and web application in JSON format.

In Python, JSON exists as a string. For example:

p = '{"name": "Bob", "languages": ["Python", "Java"]}'

It's also common to store a JSON object in a file.


Import json Module

To work with JSON (string, or file containing JSON object), you can use Python'sjson module. You need to import the module before you can use it.

import json

Parse JSON in Python

Thejson module makes it easy to parse JSON strings and files containing JSON object.


Example 1: Python JSON to dict

You can parse a JSON string usingjson.loads() method. The method returns a dictionary.

import jsonperson = '{"name": "Bob", "languages": ["English", "French"]}'person_dict = json.loads(person)# Output: {'name': 'Bob', 'languages': ['English', 'French']}print( person_dict)# Output: ['English', 'French']print(person_dict['languages'])

Here,person is a JSON string, andperson_dict is a dictionary.


Example 2: Python read JSON file

You can usejson.load() method to read a file containing JSON object.

Suppose, you have a file namedperson.json which contains a JSON object.

{"name": "Bob", "languages": ["English", "French"]}

Here's how you can parse this file:

import jsonwith open('path_to_file/person.json', 'r') as f:  data = json.load(f)# Output: {'name': 'Bob', 'languages': ['English', 'French']}print(data)

Here, we have used theopen() function to read the json file. Then, the file is parsed usingjson.load() method which gives us a dictionary nameddata.

If you do not know how to read and write files in Python, we recommend you to checkPython File I/O.


Python Convert to JSON string

You can convert a dictionary to JSON string usingjson.dumps() method.


Example 3: Convert dict to JSON

import jsonperson_dict = {'name': 'Bob','age': 12,'children': None}person_json = json.dumps(person_dict)# Output: {"name": "Bob", "age": 12, "children": null}print(person_json)

Here's a table showing Python objects and their equivalent conversion to JSON.

PythonJSON Equivalent
dictobject
list,tuplearray
strstring
int,float,intnumber
Truetrue
Falsefalse
Nonenull

Writing JSON to a file

To write JSON to a file in Python, we can usejson.dump() method.


Example 4: Writing JSON to a file

import jsonperson_dict = {"name": "Bob","languages": ["English", "French"],"married": True,"age": 32}with open('person.txt', 'w') as json_file:  json.dump(person_dict, json_file)

In the above program, we have opened a file namedperson.txt in writing mode using'w'. If the file doesn't already exist, it will be created. Then,json.dump() transformsperson_dict to a JSON string which will be saved in theperson.txt file.

When you run the program, theperson.txt file will be created. The file has following text inside it.

{"name": "Bob", "languages": ["English", "French"], "married": true, "age": 32}

Python pretty print JSON

To analyze and debug JSON data, we may need to print it in a more readable format. This can be done by passing additional parametersindent andsort_keys tojson.dumps() andjson.dump() method.


Example 5: Python pretty print JSON

import jsonperson_string = '{"name": "Bob", "languages": "English", "numbers": [2, 1.6, null]}'# Getting dictionaryperson_dict = json.loads(person_string)# Pretty Printing JSON string backprint(json.dumps(person_dict, indent = 4, sort_keys=True))

When you run the program, the output will be:

{    "languages": "English",    "name": "Bob",    "numbers": [        2,        1.6,        null    ]}

In the above program, we have used4 spaces for indentation. And, the keys are sorted in ascending order.

By the way, the default value ofindent isNone. And, the default value ofsort_keys isFalse.


Recommended Readings:

Share on:
Did you find this article helpful?

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges

[8]ページ先頭

©2009-2025 Movatter.jp