JSON standard library based on Python

Table of contents

1. Basic overview of JSON

2. JSON format

3. Precautions

4. Summary of json format

5. JSON module

5.1 Function

5.2 Data type conversion

2.3 How to use

2.4 json.dumps()

 2.5 json.dump()

2.6  json.loads()

2.7 json.load()

3. Parse the json file


1. Basic overview of JSON

JSON is language independent

JSON is self-describing and easier to understand

JSON is smaller, faster and easier to parse than XML

2. JSON format

{
  "student": 
          [
            {"name": "小明", "age": 12},
            {"name": "小红", "age": 18}
          ],
  "classroom": {"class1": "room1", "class2": "room2"}
}

3. Precautions

1. The key part of the key-value pair of json must use double quotes

2. The value part of the key-value pair of json does not allow function, undefined, NaN, but can have null

3. After the json data ends, meaningless commas are not allowed

4. Summary of json format

{"name": "admin", "age": 18}  # JSON对象


# JSON数组
{
  "student":
          [
            {"name": "小明", "age": 12},
            {"name": "小红", "age": 18}
          ],
}


5. JSON module

5.1 Function

1. Use json string to generate python object (load)

2. Use python object formatting called json string (dump)

5.2 Data type conversion

Convert python to json format, there will be changes in data types

dict--object

list,tuple--array

str--string

int,float--number

True--true

False--false

None--null

2.3 How to use

json.dumps(obj) # convert the python data type to a string in json format

json.dump(obj,fp) # Convert and save the python data type string to a file in json format

json.loads(s) # Convert a string in json format to a python type

json.load(fp) # read the data from the file in json format and convert it to python type

2.4 json.dumps()

The difference between the json format and the python format is that the print output in the python format is a single quote, and the type is dict, and the print output in the json format is double quotes, and the type is str. There is a difference in capitalization at the beginning of True.

import json

person = {"name": "小明", "age": 18, "tel": ["888888", "13555555555"], "isonly": True}
print(person)
print(type(person))
print(json.dumps(person))
print(type(json.dumps(person)))

Use parameters to format the output of the json string

Interpretation of parameters:

sort_keys # whether to sort

indent # Define the indentation distance

separators # is a tuple that defines the separator type

skipkeys # Whether to allow json strings to encode dictionary objects, the key of the dictionary is not a string type (not allowed by default)

print(json.dumps(person, sort_keys=True, indent=4, separators=(',', ':')))
import json

person = {"name": "小明", "age": 18, "tel": ["888888", "13555555555"], "isonly": True}
print(person)
print(type(person))
print(json.dumps(person, sort_keys=True, indent=4, separators=(',', ':')))
print(type(json.dumps(person)))


json_str = json.dumps(person)

with open('test.json', 'w', encoding='utf-8') as f:
    f.write(json_str)

 2.5 json.dump()

Convert python data type and save to json format file


person = {"name": "小明", "age": 18, "tel": ["888888", "13555555555"], "isonly": True}
json.dump(person, open('data.json', 'w'), sort_keys=True, indent=4, separators=(',', ':'))

 The difference between json.dumps() and json.dump writing files

dump() does not need to use the .write() method, just which dictionary and which file to write, and dumps() needs to be written using the .writer() method

If you write the dictionary into a file, dump() is easy to use, but if you don’t need to operate the file, or store the content in a database or excel, you need to use dumps() to convert the field to a string first, and then write enter.

2.6  json.loads()

Convert a string in json format to a python type

json_str = json.dumps(person, sort_keys=True, indent=4, separators=(',', ':'))
python_dict = json.loads(json_str)
print(python_dict)
print(type(python_dict))
print(python_dict.keys())
print(python_dict.values())

file operation

f = open('data.json', 'r', encoding='utf-8')
content = f.read()
python_dict = json.loads(content)
print(python_dict)

2.7 json.load()

Read data from a file in json format and convert it to a python type


python_dict = json.load(open('data.json', 'r'))
print(python_dict)
print(type(python_dict))

The difference between json.loads and json.load:

loads() wears a json string, while load() passes a file object

When using loads(), you need to read the file before using it, but load() does not

3. Parse the json file

python_dict = json.load(open('data.json', 'r'))
print(python_dict)
print(type(python_dict))

print(python_dict.keys())
print(python_dict.values())
print(python_dict['age'])

Guess you like

Origin blog.csdn.net/xiao__dashen/article/details/125398025