Read and write JSON files in Python

Sample code

import json


print('**********Export JSON file**********')

#Dictionary object(dictionary)Generate a
data = dict()
data['message'] = 'Hello, world.'
data['members'] = [
  {'name': 'Alice', 'color': '#FA3E05'},
  {'name': 'Bob',   'color': '#FFFFAA'}
]

#Get dictionary object as str type and output
print(json.dumps(data, ensure_ascii=False, indent=2))

#Output dictionary object to JSON file
with open('mydata.json', mode='wt', encoding='utf-8') as file:
  json.dump(data, file, ensure_ascii=False, indent=2)


print('**********Read JSON file**********')

#Generate a text stream from a JSON file
with open('mydata.json', mode='rt', encoding='utf-8') as file:
  print('file: ' + str(file))

  #Dictionary object(dictionary)Get
  data = json.load(file)
  print('data: ' + str(type(data)))

  #Output the required part from JSON data
  print('message: ' + data['message'])
  for member in data['members']:
    print(member['name'] + ': ' + member['color'])

Execution result

The result of running with Python 3.8.2.

**********Export JSON file**********
{
  "message": "Hello, world.",
  "members": [
    {
      "name": "Alice",
      "color": "#FA3E05"
    },
    {
      "name": "Bob",
      "color": "#FFFFAA"
    }
  ]
}
**********Read JSON file**********
file: <_io.TextIOWrapper name='mydata.json' mode='rt' encoding='utf-8'>
data: <class 'dict'>
message: Hello, world.
Alice: #FA3E05
Bob: #FFFFAA

Output JSON file

{
  "message": "Hello, world.",
  "members": [
    {
      "name": "Alice",
      "color": "#FA3E05"
    },
    {
      "name": "Bob",
      "color": "#FFFFAA"
    }
  ]
}

Reference material

json ---JSON encoders and decoders — Python 3 \ .8 \ .2 documentation

The json API is familiar to users of the standard library marshal and pickle.

Built-in — Python 3 \ .8 \ .2 documentation

Dictionaries can be created by enclosing a comma-separated list of key: value pairs in curly braces. For example: {'jack': 4098,'sjoerd': 4127} or {4098:'jack', 4127:'sjoerd'}. Alternatively, you can create it with the dict constructor.

Recommended Posts

Read and write JSON files in Python
Reading and writing CSV and JSON files in Python
[Python3] Read and write with datetime isoformat with json
Read and write single precision floating point in Python
Read and write files with Slackbot ~ Bot development with Python ~
Read and write NFC tags in python using PaSoRi
Write JSON Schema in Python DSL
Manipulate files and folders in Python
Read and use Python files from Python
Handling of JSON files in Python
Read files in parallel with Python
Export and output files in Python
Create and read messagepacks in Python
[Python] Use this to read and write wav files [wavio]
Write O_SYNC file in C and Python
Read and write csv files with numpy
Reading and writing JSON files with Python
Read DXF in python
Handling json in python
Write Python in MySQL
Read JSON with Python and output as CSV
POST JSON in Python and receive it in PHP
Get options in Python from both JSON files and command line arguments
Easily format JSON in Python
Write Pandoc filters in Python
Write beta distribution in Python
Write python in Rstudio (reticulate)
Read Euler's formula in Python
Include and use external Kv files in Python Kivy
Read and write a file
Read Outlook emails in Python
Write tests in Python to profile and check coverage
Stack and Queue in Python
Mutual conversion between JSON and YAML / TOML in Python
Read json file with Python, format it, and output json
Write and read a file
Unittest and CI in Python
Recursively search for files and directories in Python and output
Read Fortran output in python
Read json data with python
Compare read / write speed and capacity of csv, pickle, joblib, parquet in python environment
Easily write JSON and Python dataclass conversions with quicktype and dacite
[R] [Python] Memo to read multiple csv files in multiple zip files
Read json in C # and convert to dictionary type (forced)
Transpose CSV files in Python Part 1
Write a binary search in Python
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
Difference between == and is in python
View photos in Python and html
Read Protocol Buffers data in Python3
Sorting algorithm and implementation in Python
Write an HTTP / 2 server in Python
About dtypes in Python and Cython
Dynamically load json type in python
Write A * (A-star) algorithm in Python
Download Google Drive files in Python
Read PNG chunks in Python (class)
Assignments and changes in Python objects
Check and move directories in Python
Preserve and read order in PyYAML