- Работа с файлами в формате JSON#
- Чтение#
- json.load #
- json.loads #
- Запись#
- json.dumps #
- json.dump #
- Дополнительные параметры методов записи#
- Изменение типа данных#
- How to Modify JSON File in Python?
- Hardik Savani
- We are Recommending you
- 💥py-jsoneditor💥
- Screenshot
- Installation
- Python example
- Formats you can pass the JSON as
- Python Api
- CLI options
- Build
Работа с файлами в формате JSON#
JSON (JavaScript Object Notation) — это текстовый формат для хранения и обмена данными.
JSON по синтаксису очень похож на Python и достаточно удобен для восприятия.
Как и в случае с CSV, в Python есть модуль, который позволяет легко записывать и читать данные в формате JSON.
Чтение#
"access": [ "switchport mode access", "switchport access vlan", "switchport nonegotiate", "spanning-tree portfast", "spanning-tree bpduguard enable" ], "trunk": [ "switchport trunk encapsulation dot1q", "switchport mode trunk", "switchport trunk native vlan 999", "switchport trunk allowed vlan" ] >
Для чтения в модуле json есть два метода:
- json.load — метод считывает файл в формате JSON и возвращает объекты Python
- json.loads — метод считывает строку в формате JSON и возвращает объекты Python
json.load #
Чтение файла в формате JSON в объект Python (файл json_read_load.py):
import json with open('sw_templates.json') as f: templates = json.load(f) print(templates) for section, commands in templates.items(): print(section) print('\n'.join(commands))
$ python json_read_load.py access switchport mode access switchport access vlan switchport nonegotiate spanning-tree portfast spanning-tree bpduguard enable trunk switchport trunk encapsulation dot1q switchport mode trunk switchport trunk native vlan 999 switchport trunk allowed vlan
json.loads #
Считывание строки в формате JSON в объект Python (файл json_read_loads.py):
import json with open('sw_templates.json') as f: file_content = f.read() templates = json.loads(file_content) print(templates) for section, commands in templates.items(): print(section) print('\n'.join(commands))
Результат будет аналогичен предыдущему выводу.
Запись#
Запись файла в формате JSON также осуществляется достаточно легко.
Для записи информации в формате JSON в модуле json также два метода:
- json.dump — метод записывает объект Python в файл в формате JSON
- json.dumps — метод возвращает строку в формате JSON
json.dumps #
Преобразование объекта в строку в формате JSON (json_write_dumps.py):
import json trunk_template = [ 'switchport trunk encapsulation dot1q', 'switchport mode trunk', 'switchport trunk native vlan 999', 'switchport trunk allowed vlan' ] access_template = [ 'switchport mode access', 'switchport access vlan', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable' ] to_json = 'trunk': trunk_template, 'access': access_template> with open('sw_templates.json', 'w') as f: f.write(json.dumps(to_json)) with open('sw_templates.json') as f: print(f.read())
Метод json.dumps подходит для ситуаций, когда надо вернуть строку в формате JSON. Например, чтобы передать ее API.
json.dump #
Запись объекта Python в файл в формате JSON (файл json_write_dump.py):
import json trunk_template = [ 'switchport trunk encapsulation dot1q', 'switchport mode trunk', 'switchport trunk native vlan 999', 'switchport trunk allowed vlan' ] access_template = [ 'switchport mode access', 'switchport access vlan', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable' ] to_json = 'trunk': trunk_template, 'access': access_template> with open('sw_templates.json', 'w') as f: json.dump(to_json, f) with open('sw_templates.json') as f: print(f.read())
Когда нужно записать информацию в формате JSON в файл, лучше использовать метод dump.
Дополнительные параметры методов записи#
Методам dump и dumps можно передавать дополнительные параметры для управления форматом вывода.
По умолчанию эти методы записывают информацию в компактном представлении. Как правило, когда данные используются другими программами, визуальное представление данных не важно. Если же данные в файле нужно будет считать человеку, такой формат не очень удобно воспринимать.
К счастью, модуль json позволяет управлять подобными вещами.
Передав дополнительные параметры методу dump (или методу dumps), можно получить более удобный для чтения вывод (файл json_write_indent.py):
import json trunk_template = [ 'switchport trunk encapsulation dot1q', 'switchport mode trunk', 'switchport trunk native vlan 999', 'switchport trunk allowed vlan' ] access_template = [ 'switchport mode access', 'switchport access vlan', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable' ] to_json = 'trunk': trunk_template, 'access': access_template> with open('sw_templates.json', 'w') as f: json.dump(to_json, f, sort_keys=True, indent=2) with open('sw_templates.json') as f: print(f.read())
Теперь содержимое файла sw_templates.json выглядит так:
"access": [ "switchport mode access", "switchport access vlan", "switchport nonegotiate", "spanning-tree portfast", "spanning-tree bpduguard enable" ], "trunk": [ "switchport trunk encapsulation dot1q", "switchport mode trunk", "switchport trunk native vlan 999", "switchport trunk allowed vlan" ] >
Изменение типа данных#
Еще один важный аспект преобразования данных в формат JSON: данные не всегда будут того же типа, что исходные данные в Python.
Например, кортежи при записи в JSON превращаются в списки:
In [1]: import json In [2]: trunk_template = ('switchport trunk encapsulation dot1q', . 'switchport mode trunk', . 'switchport trunk native vlan 999', . 'switchport trunk allowed vlan') In [3]: print(type(trunk_template)) In [4]: with open('trunk_template.json', 'w') as f: . json.dump(trunk_template, f, sort_keys=True, indent=2) . In [5]: cat trunk_template.json [ "switchport trunk encapsulation dot1q", "switchport mode trunk", "switchport trunk native vlan 999", "switchport trunk allowed vlan" ] In [6]: templates = json.load(open('trunk_template.json')) In [7]: type(templates) Out[7]: list In [8]: print(templates) ['switchport trunk encapsulation dot1q', 'switchport mode trunk', 'switchport trunk native vlan 999', 'switchport trunk allowed vlan']
Так происходит из-за того, что в JSON используются другие типы данных и не для всех типов данных Python есть соответствия.
Таблица конвертации данных Python в JSON:
How to Modify JSON File in Python?
In this example, you will learn python read and write to same json file. We will look at an example of append json file in python. We will use python open json file and modify. I would like to show you how to update json file in python. Here, Create a basic example of how to edit a json file in python.
There are several ways to update the JSON file in python. Here, i will give you very simple example of edit JSON file using open() , append() , dump() and close() functions. so let’s see a simple example below:
You can use these examples with python3 (Python 3) version.
I simply created data.json file with content as like below showed you. we will open that file and read it, Then write some more content on it.
import json # Read Existing JSON File with open('data.json') as f: data = json.load(f) # Append new object to list data data.append(< "ID": 4, "Name": "Paresh Patel", "email": "paresh@gmail.com" >) # Append new object to list data data.append(< "ID": 5, "Name": "Rakesh Patel", "email": "rakesh@gmail.com" >) # Create new JSON file with open('data.json', 'w') as f: json.dump(data, f, indent=2) # Closing file f.close()
After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:
Hardik Savani
I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python Create JSON File from Dict Example
- Python Create JSON File from List Example
- How to Write a JSON File in Python?
- How to Read a JSON File in Python?
- How to Create a JSON File in Python?
- Python Read CSV File Without Header Example
- How to Read a CSV File in Python?
- Python Read Text File into List Example
- How to Read Text File Line by Line in Python?
- Python Create Text File in Specific Directory Example
- Python List Add Element at Beginning Example
- Python Create Zip Archive from Directory Example
💥py-jsoneditor💥
When working with JSON data, You often need to get a structured view of the JSON in order to be able to work with it. There’s an online tool https://jsoneditoronline.org/ which I used for this, but copying/pasting all the time got frustrating pretty quickly, This is why I created this package which you can launch right from Python or from the command line.
Screenshot
Installation
Python example
In python you can simply import jsoneditor and call the editjson function, the first argument is going to be the data. See Formats you can pass the JSON as for all the formats you can pass the JSON in. See Python api for a full list of addtional arguments that you can pass to editjson .
From the command line you can either pass the data as an argument as so:
Or you can pipe it in like so:
curl https://jsonplaceholder.typicode.com/comments jsoneditor
Or you can use what you have in your clipboard like so:
See Formats you can pass the JSON as for all the formats you can pass the JSON in.
Refer to CLI options for a list of all cli options. Alternatively you can run jsoneditor —help from your terminal to see it.
Formats you can pass the JSON as
You can pass the json in any of the following formats:
- as valid json string. Example:
- as a python dict. Example:
- as a url the points to valid json. Example: https://jsonplaceholder.typicode.com/comments
- as a file path that is valid json. Example: data.json
Python Api
parameter | type | optional | description |
---|---|---|---|
data | Any | ❌ | The data in any of these formats. |
callback | callable | ✔️ | If you provide this argument you will have a ✅ button which will trigger this callback. |
options | dict | ✔️ | Options to pass the the jsoneditor object. See here |
additional_js | str | ✔️ | You can pass some JavaScript to run on the client side. You can interact with the editor by accessing the window.editor variable. |
keep_running | bool | ✔️ | Whether to keep the server running. Defaults to False . |
run_in_thread | bool | ✔️ | Whether to run the server in a separate thread. Defaults to False . |
is_csv | bool | ✔️ | Whether the data is csv data. Defaults to False . |
is_yaml | bool | ✔️ | Whether the data is yaml data. Defaults to False . |
is_ndjson | bool | ✔️ | Whether the data is Newline Delimited JSON . Defaults to False . |
is_js_object | bool | ✔️ | Whether the data is a JavaScript Object. Defaults to False . |
title | str | ✔️ | A title to display in the browser. |
port | int | ✔️ | specify which port to use. |
CLI options
parameter | description |
---|---|
data | The data in any of these formats |
-o | Add a button that will output the json back to the console |
-b | Keep running in background |
-c | Get JSON input from clipboard |
-k | Keep alive |
-e | Edit mode |
-n | Don’t launch browser |
-p | Server port |
—out | File to output when in edit mode |
-t | Title to display in browser window |
—csv | Input is CSV |
—yaml | Input is YAML |
—js | Input is a JavaScript Object |
—ndjson | Input is Newline Delimited JSON |