How to save json file python

Python Write JSON to File

You can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively.

Following is a step by step process to write JSON to file.

  1. Prepare JSON string by converting a Python Object to JSON string using json.dumps() function.
  2. Create a JSON file using open(filename, ‘w’) function. We are opening file in write mode.
  3. Use file.write(text) to write JSON content prepared in step 1 to the file created in step 2.
  4. Close the JSON file.

Examples

1. Write JSON (Object) string to File

In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json.

Python Program

import json aDict = jsonString = json.dumps(aDict) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close()

Run the above program, and data.json will be created in the working directory.

2. Write JSON (list of objects) to a file

In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json.

Python Program

import json aList = [, , ] jsonString = json.dumps(aList) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close()

Run the above program, and data.json will be created in the working directory.

Читайте также:  Java abstract class getter

Summary

In this Python JSON Tutorial, we learned how to write JSON to File, using step by step process and detailed example programs.

Источник

Работа с файлами в формате 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:

Источник

Save and load Python data with JSON

The JSON format saves you from creating your own data formats, and is particularly easy to learn if you already know Python. Here’s how to use it with Python.

Databases as a service

JSON stands for JavaScript Object Notation. This format is a popular method of storing data in key-value arrangements so it can be parsed easily later. Don’t let the name fool you, though: You can use JSON in Python—not just JavaScript—as an easy way to store data, and this article demonstrates how to get started.

First, take a look at this simple JSON snippet:

That’s pure JSON and has not been altered for Python or any other language. Yet if you’re familiar with Python, you might notice that this example JSON code looks an awful lot like a Python dictionary. In fact, the two are very similar: If you are comfortable with Python lists and dictionaries, then JSON is a natural fit for you.

Storing data in JSON format

You might consider using JSON if your application needs to store somewhat complex data. While you may have previously resorted to custom text configuration files or data formats, JSON offers you structured, recursive storage, and Python’s JSON module offers all of the parsing libraries necessary for getting this data in and out of your application. So, you don’t have to write parsing code yourself, and other programmers don’t have to decode a new data format when interacting with your application. For this reason, JSON is easy to use, and ubiquitous.

Here is some sample Python code using a dictionary within a dictionary:

#!/usr/bin/env python3 import json # instantiate an empty dict team = <> # add a team member team['tux'] = team['beastie'] = team['konqi'] =

This code creates a Python dictionary called team. It’s empty initially (you can create one that’s already populated, but that’s impossible if you don’t have the data to put into the dictionary yet).

To add to the dict object, you create a key, such as tux, beastie, or konqi in the example code, and then provide a value. In this case, the value is another dictionary full of player statistics.

Dictionaries are mutable. You can add, remove, and update the data they contain as often as you please. This format is ideal storage for data that your application frequently uses.

Saving data in JSON format

If the data you’re storing in your dictionary is user data that needs to persist after the application quits, then you must write the data to a file on disk. This is where the JSON Python module comes in:

with open('mydata.json', 'w') as f: json.dump(team, f) 

This code block creates a file called mydata.json and opens it in write mode. The file is represented with the variable f (a completely arbitrary designation; you can use whatever variable name you like, such as file, FILE, output, or practically anything). Meanwhile, the JSON module’s dump function is used to dump the data from the dict into the data file.

Saving data from your application is as simple as that, and the best part about this is that the data is structured and predictable. To see, take a look at the resulting file:

$ cat mydata.json , "beastie": , "konqi": > 

Reading data from a JSON file

If you are saving data to JSON format, you probably want to read the data back into Python eventually. To do this, use the Python JSON module’s json.load function:

#!/usr/bin/env python3 import json f = open('mydata.json') team = json.load(f) print(team['tux']) print(team['tux']['health']) print(team['tux']['level']) print(team['beastie']) print(team['beastie']['health']) print(team['beastie']['level']) # when finished, close the file f.close() 

This function implements the inverse, more or less, of saving the file: an arbitrary variable (f) represents the data file, and then the JSON module’s load function dumps the data from the file into the arbitrary team variable.

The print statements in the code sample demonstrate how to use the data. It can be confusing to compound dict key upon dict key, but as long as you are familiar with your own dataset, or else can read the JSON source to get a mental map of it, the logic makes sense.

Of course, the print statements don’t have to be hard-coded. You could rewrite the sample application using a for loop:

for i in team.values(): print(i) 

Using JSON

As you can see, JSON integrates surprisingly well with Python, so it’s a great format when your data fits in with its model. JSON is flexible and simple to use, and learning one basically means you’re learning the other, so consider it for data storage the next time you’re working on a Python application.

Источник

Оцените статью