Working with data in JSON format using Python

  • 2021-07-24 11:14:37
  • OfStack

If you don't want to create a data format to store data from scratch, JSON is a good choice. If you know something about Python, you will get twice the result with half the effort. Let's introduce how to use Python to process JSON data under 1.

The full name of JSON is JavaScript object representation JavaScript Object Notation . This is a format for storing data in the form of key-value pairs, and it is easy to parse, so it has become a widely used data format. Also, don't let the name JSON make sense. JSON is not only used in JavaScript, it can also be used in other languages. How it is used in Python is described below.

First, we give an example of JSON:


{
 "name":"tux",
 "health":"23",
 "level":"4"
}

The above is a native JSON data independent of the programming language. Anyone familiar with Python will see that this JSON data looks very much like the dictionary dictionary in Python. The two are indeed very similar. If you have a definite understanding of the list and dictionary data structures in Python, it is not difficult to understand JSON.

Use a dictionary to store data

If your application needs to store complex data, consider using JSON format. JSON provides a more structured and recursive storage format than the custom-formatted text configuration files you might have used before. At the same time, the json module that comes with Python already provides all the parsing libraries needed to import/export JSON data into/out of applications. Therefore, you don't need to write your own code to parse JSON, and other developers don't need to parse new data formats when interacting with your application. It is for this reason that JSON is widely used in data exchange.

The following is a code for using nested dictionaries in Python:


#!/usr/bin/env python3
import json
# instantiate an empty dict
team = {}
# add a team member
team['tux'] = {'health': 23, 'level': 4}
team['beastie'] = {'health': 13, 'level': 6}
team['konqi'] = {'health': 18, 'level': 7}

This code declares a dictionary named team and initializes it to an empty dictionary.

If you want to add content to this dictionary, you first need to create 1 key, such as tux, beastie, konqi in the above example, and then provide corresponding values for these keys 11. The values in the above example are served by 1 dictionary containing gamer information.

A dictionary is a variable. Data in the dictionary can be added, deleted or updated at any time. This feature makes dictionaries an excellent choice for applications to store data.

Using JSON format to store data

If the data stored in the dictionary needs to be persisted, the data needs to be written to a file. At this time, you need to use the json module in Python:


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

The above code first creates a file named mydata. json, and then opens it in write mode. The opened file is represented by the variable f (of course, it can also use any name you like, such as file, output, etc.). The dump () method in the json module is used to output a dictionary to a file.

Exporting data from an application is as simple as that, and the derived data is structured and understandable. You can now view the exported data:


$ cat mydata.json
{"tux": {"health": 23, "level": 4}, "beastie": {"health": 13, "level": 6}, "konqi": {"health": 18, "level": 7}}

Read data from an JSON file

If the data has been exported to a file in JSON format, it may also be necessary to read the data back into the application. At this point, you can use the load () method in the Python json module:


#!/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 method implements the opposite operation to saving files. Use a variable f to represent an open file, and then use the load () method in the json module to read the data in the file and store it in the team variable.

print () shows how to view the read data. It is possible to iteratively call dictionary keys in an overly complex dictionary, but as long as you are familiar with the structure of the whole data, you can slowly explore the logic.

Of course, the way print () is used here is too inflexible. You can rewrite it to use the for loop:


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

Using JSON

As mentioned above, JSON data can be easily processed in Python. So as long as your data conforms to the JSON schema, you can choose to use JSON. JSON is very flexible and easy to use, so try it once the next time you use Python.

via: https://opensource.com/article/19/7/save-and-load-data-python-json

Summarize


Related articles: