Как читать JSON-файл в Python

How do I read a JSON file in Python?

Hello everybody! Today we’ll try to figure it out: what is JSON and how to read a JSON file in Python?

First, some facts:

  • JSON stands for JavaScript Object Notation
  • This is a data exchange format in which you can transfer data from client to server and from server to client
  • It is also used for communication between applications
  • JSON is extremely important for application development, especially when you are working with API Rest
  • It is based on a subset of Java Script
  • It’s easy to read and write

We got acquainted with the theory, and now we will find out the basic syntax rules when working with the JSON format:

  • JSON uses key-value pairs – {“name”: “Vasya”}
  • JSON uses double quotes around the key

Usually in tutorials they talk about a team with data on salary, place of residence and all that stuff. Let’s not break the tradition, and imagine a team of 5 employees: Vasya, Sasha, Petya, Dasha, Masha. Each employee receives a certain salary, which means that we can create our own JSON file (let’s call the file personal.json), which will represent a list of employees + their salary:

{
"personal" :   [
{
"name" :   "Vasya" ,
"salary" :   5000
} ,
 
{
"name" :   "Sacha" ,
"salary" :   6000
} ,
 
{
"name" :   "Peter" ,
"salary" :   9000
 
} ,
 
{
"name" :   "Dascha" ,
"salary" :   10000
 
},
 
{
"name" :   "Mascha" ,
"salary" :   11000
 
}
]
}

as you can see, the name field is responsible for the employee’s name, and the salary field is responsible for the salary level, but the very name of this data array is personal (indicated at the very top). We have a data file, but how to read it? To do this, take a look at the code below:
import json #Подключаем библиотеку, отвечающую за работу с JSON

with open(‘personal.json’, ‘r’, encoding=’utf-8′) as f: #открываем файл personal.json и указываем его кодировку – что бы можно было работать с русскими буквами
text = json.load(f) #загоняем в переменную все, что получилось в результате работы библиотеки
print(text) #выводим результат на экран

Если вы запустите код – то получите на экране нечто вроде:
{‘personal’: [{‘name’: ‘Вася’, ‘salary’: 5000}, {‘name’: ‘Саша’, ‘salary’: 6000}, {‘name’: ‘Петя’, ‘salary’: 9000}, {‘name’: ‘Даша’, ‘salary’: 10000}, {‘name’: ‘Маша’, ‘salary’: 11000}]}

Согласитесь – читать и разбирать подобные данные крайне сложно. Для упрощения работы в подобном случае часто используют библиотеку pprint, которая окультуривает выдачу в подобных случаях. В этом случае наш код будет выглядеть так:

  1. import json #connected a library for working with json
  2. from pprint import pprint #connected Pprint for the beauty of text 
  3. with open('personal.json', 'r', encoding='utf-8') as f: #open file with data
  4.     text = json.load(f) #added all to variable
  5.     pprint(text) #input result to console

As a result, the output looks like this:

  1. {'personal': [{'name': 'Vasya', 'salary': 5000},
  2.               {'name': 'Sacha', 'salary': 6000},
  3.               {'name': 'Peter', 'salary': 9000},
  4.               {'name': 'Dascha', 'salary': 10000},
  5.               {'name': 'Mascha', 'salary': 11000}]}

And now we will display the data in its pure form – the name of the employee + salary. Then the code will look like this:

  1. import json #added library for working with json
  2.  
  3. with open('personal.json', 'r', encoding='utf-8') as f: #open file with data
  4.     text = json.load(f) #added all data to variable
  5.     print(text) #export all result to console
  6.  
  7. for txt in text['personal']: #created a loop that will run line by line
  8.     print(txt['name'], ':', txt['salary']) #and display everything that is in the value of the name and salary keys

Actually … one could say that that’s all, that’s enough for today, but in the end I’ll tell you how to read not json files, but strings. For example, we will have a json string:
stroke = ‘{“food”: “banana”}’
If we try to display it on the screen, we get:
{“food”: “banana”} – which, in general, conveys the essence, but does not correspond to the rules 🙂 The loads function is used to display a json-string. In code form, it looks like this:

  1. import json #connect the library to work with json
  2. stroke = '{"food": "banana"}' #json-stroke
  3. stroke_s = json.loads(stroke) #we drive the result of reading the json string into a variable
  4. print(stroke_s) #display the result on the screen

That’s all 🙂 Thank you for your attention! And yes – we will figure out how to write to a json file a little later 🙂
Have questions? Ask on mail, or Telegram 🙂