If you don’t want to create a data format to store data from scratch, JSON is a great choice. If you know something about Python, it’s even more effective. Here’s how to use Python to process JSON data.

Cloud and databsae incons

JSON stands for JavaScript Object Notation. This is a format that stores data as key-value pairs and is easy to parse, making it a widely used data format. Also, don’t be fooled by the JSON name; JSON isn’t just used in JavaScript; it can be used in other languages as well. How it is used in Python is described below.

Let’s start with a JSON example:

{
    "name":"tux"."health":"23"."level":"4"
}
Copy the code

Above is native JSON data that is programming language-independent. Those familiar with Python will recognize that this JSON data looks a lot like the dictionary in Python. The similarities are indeed very similar, and if you have some understanding of list and dictionary data structures in Python, JSON is not difficult to understand.

Use dictionaries to store data

If your application needs to store complex data, consider using JSON. JSON provides a more structured and recursive storage format than custom formatted text configuration files you might have used. Meanwhile, Python’s own JSON module already provides all the parsing libraries needed to import/export JSON data into and out of applications. As a result, you don’t have to write your own code to parse JSON, and other developers don’t have to parse the new data format when they interact with your application. It is for this reason that JSON is widely used for data exchange.

Here is the 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} :Copy the code

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

To add content to the dictionary, you first create a key, such as tux, Beastie, konqi in the example above, and then provide the corresponding values for each key. The values in the above example are represented by a series of dictionaries containing information about game players.

A dictionary is a mutable variable. The data in the dictionary can be added, deleted, or updated at any time. Such features make dictionaries an excellent choice for storing data in applications.

Store data in JSON format

If data stored in a dictionary needs to be persisted, it needs to be written to a file. This is where the json module in Python comes in:

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

The above code first creates a file named mydata.json, and then opens it in write mode, using the variable F (or whatever you like, file, output, etc.). The dump() method in the JSON module is used to export a dictionary to a file.

Exporting data from an application is as simple as that, and the exported 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}} :Copy the code

Read data from a JSON file

If you have exported the data to a file in JSON format, you may need 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()
Copy the code

This method does roughly the opposite of saving the file. Use a variable f to represent the open file, and then use the LOAD () method in the JSON module to read the data from the file and store it in the team variable.

Print () shows how to view the read data. Iterating over the dictionary keys in an overly complex dictionary can get you slightly out of shape, but once you’re familiar with the structure of the data, you can start to figure out the logic.

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

for i in team.values():
    print(i)
Copy the code

Using JSON

As mentioned above, JSON data can be easily manipulated 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 give it a try the next time you use Python.


Via: opensource.com/article/19/…

By Seth Kenlon (lujun9972

This article is originally compiled by LCTT and released in Linux China