Sesame HTTP: JSON file storage

JSON, the full name of JavaScript Object Notation, is JavaScript Object Notation. It represents data through a combination of objects and arrays. It has a simple structure but a very high degree of structure. It is a lightweight data exchange format. In this section, we will learn how to save data to JSON file using Python.

1. Objects and arrays

In the JavaScript language, everything is an object. Therefore, any supported type can be represented by JSON, such as strings, numbers, objects, arrays, etc., but objects and arrays are two special and commonly used types, and they are briefly introduced below.

  • Object{} : It is the content wrapped in curly braces in JavaScript, and the data structure is {key1:value1, key2:value2, ...}a key-value pair structure. In object-oriented languages, it keyis the property of the object and valuethe corresponding value. Key names can be represented using integers and strings. The type of the value can be any type.
  • Array : Array is the content enclosed in square brackets in JavaScript, []and the data structure is ["java", "javascript", "vb", ...]the index structure. In JavaScript, arrays are a special data type that can also use key-value pairs like objects, but are still more indexed. Likewise, the type of the value can be any type.

So, a JSON object can be written as follows:

[{
    "name": "Bob",
    "gender": "male",
    "birthday": "1992-10-18"
}, {
     "name": "Selina",
    "gender": "female",
    "birthday": "1995-10-18"
}]

Surrounded by square brackets is equivalent to a list type, each element in the list can be of any type, in this example it is a dictionary type, surrounded by curly brackets.

JSON can be freely combined from the above two forms, can be nested infinitely, and has a clear structure. It is an excellent way of data exchange.

2. Read JSON

Python provides us with an easy-to-use library to read and write JSON files. We can call the library's loads()methods to convert JSON text strings into JSON objects, and use dumps()methods to convert JSON objects into text strings.

For example, here is a string in JSON form, which is a strtype that we use Python to convert into a manipulable data structure like a list or a dictionary:

import json

str = '''
[{
    "name": "Bob",
    "gender": "male",
    "birthday": "1992-10-18"
}, {
    "name": "Selina",
    "gender": "female",
    "birthday": "1995-10-18"
}]
'''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))

The results are as follows:

<class 'str'>
[{'name': 'Bob', 'gender': 'male', 'birthday': '1992-10-18'}, {'name': 'Selina', 'gender': 'female', 'birthday': '1995-10-18'}]
<class 'list'>

Here use loads()method to convert string to JSON object. Since the outermost layer is square brackets, the final type is the list type.

In this way, we can use the index to get the corresponding content. For example, if you want to get the attribute in the first element name, you can use the following method:

data[0]['name']
data[0].get('name')

The results obtained are:

Bob

By adding 0 index to square brackets, you can get the first dictionary element, and then call its key name to get the corresponding key value. There are two ways to get the key value, one is to add the key name in square brackets, and the other is to get()pass in the key name through the method. The method is recommended here get(), so that if the key name does not exist, no error will be reported and it will be returned None. In addition, the get()method can also pass in a second parameter (that is, the default value), for example:

data[0].get('age')
data[0].get('age', 25)

The results are as follows:

None
25

Here we try to get the age age. In fact, the key name does not exist in the original dictionary, and it will be returned by default None. If the second parameter (that is, the default value) is passed in, that default value is returned if it does not exist.

It is worth noting that JSON data needs to be surrounded by double quotes, not single quotes. For example, an error will occur if expressed in the following form:

import json

str = '''
[{
    'name': 'Bob',
    'gender': 'male',
    'birthday': '1992-10-18'
}]
'''
data = json.loads(str)

The results are as follows:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 5 (char 8)

A JSON parsing error message will appear here. This is because the data is surrounded by single quotes. Please pay attention that the representation of the JSON string requires double quotes, otherwise the loads()method will fail to parse.

If the content is read from JSON text, for example, there is a data.text file, whose content is the JSON string just defined, we can read the content of the text file first, and then use the loads()method to convert:

import json

with open('data.json', 'r') as file:
    str = file.read()
    data = json.loads(str)
    print(data)

The results are as follows:

[{'name': 'Bob', 'gender': 'male', 'birthday': '1992-10-18'}, {'name': 'Selina', 'gender': 'female', 'birthday': '1995-10-18'}]

In this section, we learned about the method of reading and writing JSON files with Python, which is often used in data parsing later, and it is recommended to be proficient.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325806435&siteId=291194637