Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the json standard library of Python

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

In this article, the editor introduces in detail "how to use Python's json standard library". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use Python's json standard library" can help you solve your doubts.

1. An overview of the basics of JSON 1. What is JSON?

JSON (full name: JavaScript Object Notation object representation) is a lightweight text data interchange format. The data format of JSON is actually a dictionary format in python, which can contain an array enclosed in square brackets, that is, a list in python.

JSON is language independent

JSON is self-descriptive and easier to understand

JSON is smaller, faster and easier to parse than XML

Crawlers often get interface data, which is in JSON format

2. What does JSON look like?

Syntax format: {key1:value1, key2:value2,} key-value pairs (separated by colons), connected by commas

Simple case: JSON object

{"name": "Xiaoming", "age": 18}

Complex case: JSON array

{"student": [{"name": "Xiao Ming", "age": 11}, {"name": "Xiao Hong", "age": 10}], "classroom": {"class1": "room1", "class2": "room2"} 3, points for attention

1. The key part of the key-value pair of json must be wrapped in double quotation marks, not even single quotation marks (so if a keyword appears in the key, it is also characterized), while there is no mandatory requirement for objects in js (so keywords are not allowed in the key).

2. In the value part of the key-value pair of json, the function function,undefined,NaN is not allowed, but it can appear in the values of objects in null,js.

3. After the end of json data, meaningless commas are not allowed, such as {"name": "admin", "age": 18,}. Look at the comma after the end of the data, which is not allowed.

4. Summary of json format

The correct json format is as follows:

# format 1:JSON object {"name": "admin", "age": 18} # format 2:JSON array {"student": [{"name": "Xiao Ming", "age": 18}, {"name": "Xiao Hong", "age": 16}, {"name": "Xiao Hei", "age": 20}]}

The wrong json format is as follows:

II. Json module 1. Function

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

2. Format the python object into an ison string (dump)

2. Data type conversion

When you convert data from Python to json format, there will be changes in the data type, as shown in the following table:

PythonJSONdictobjectlist, tuplearraystrstringint, float, int- & float-derived EnumsnumberTruetrueFalsefalseNonenull

Conversely, convert the json format to the python built-in type, as shown in the following table:

JSONPythonobjectdictarrayliststringstrnumber (int) intnumber (real) floattrueTruefalseFalsenullNone3, usage

The use of the json module is actually very simple. In most cases, we only need to use the following four methods:

The method function json.dumps (obj) converts the python data type to a string in json format. Json.dump (obj, fp) converts python data types and saves them to a file in son format. Json.loads (s) converts a string in json format to the type of python. Json.load (fp) reads data from a file in json format and converts it to the type of python. 4. Json.dumps ()

Converts the python data type to a string in json format.

Syntax format: json.dumps (obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, * * kw)

> import json# Python Dictionary > > person = {"name": "Xiaoming", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} > print (person) {'name':' Xiaoming', 'age': 30,' tel': ['8888', '13511111111'], 'isonly': True} > type (person) > > jsonStr = json.dumps (person) > print (jsonStr) {"name": "\ u5c0f\ u660e" "age": 30, "tel": ["888888", "1351111111"], "isonly": true} > > type (jsonStr)

From the above, we can see that the difference between json format and Python format is that the printout in python format is in single quotation marks and the type is dict. The json format printout is in double quotes and the type is: str. The beginning of a True is case-sensitive.

Use parameters to make the JSON string format the output:

> > print (json.dumps (person, sort_keys=True, indent=4, separators= (',',':)) {"age": 30, "isonly": true, "name": "\ u5c0f\ u660e", "tel": ["888888", "1351111111"]}

Parameter interpretation:

Sort_keys: whether to sort

Indent: define indent distanc

Separators: is a tuple that defines the type of delimiter

Skipkeys: whether or not to allow JSON strings to encode dictionary objects, the dictionary's key is not a string type (not allowed by default)

Modify the separator type:

> print (json.dumps (person, sort_keys=True, indent=4, separators= ('!', -')) {"age"-30! "isonly"-true! "name"-"\ u5c0f\ u660e"! "tel"-[888888 "!" 1351111111 "]

File operation:

Import jsonperson = {"name": "Xiaoming", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} jsonStr = json.dumps (person) with open ('test.json', 'walled, encoding='utf-8') as f: # Open file f.write (jsonStr) # write the converted json string in the file

View the generated new file:

5. Json.dump ()

Convert and save the python data type to a file in son format.

Syntax format: json.dump (obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, * * kw)

Import jsonperson = {"name": "Xiaoming", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} json.dump (person, open ('data.json','))

View the generated new file:

Use parameters to make the JSON string format the output:

Import jsonperson = {"name": "Xiaoming", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} json.dump (person, open ('data.json', 'w'), sort_keys=True, indent=4, separators= (',',':'))

View the file again:

The difference between json.dumps and json.dump writing to a file:

Dump () does not need to use the .write () method, just write that dictionary, that file, while dumps () needs to be written using the .write () method.

Dump () works well if you write the dictionary to a file, but if you don't need to manipulate the file, or if you need to store the contents in the database he excel, you need to use dumps () to convert the dictionary to a string before writing

6. Json.loads ()

Converts a string in json format to the type of python.

Syntax format: json.loads (s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, * * kw)

> import json# Python Dictionary > > person = {"name": "Xiaoming", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} > print (person) {'name':' Xiaoming', 'age': 30,' tel': ['8888', '13511111111'], 'isonly': True} > type (person) > > jsonStr = json.dumps (person) > print (jsonStr) {"name": "\ u5c0f\ u660e" "age": 30, "tel": ["888888", "1351111111"], "isonly": true} > type (jsonStr) # json string is converted into Python dictionary > python_obj = json.loads (jsonStr) > print (python_obj) {'name':' Xiaoming', 'age': 30,' tel': ['888888', '13511111111'] 'isonly': True} > print (type (python_obj)) # all key of print dictionary > print (python_obj.keys ()) dict_keys ([' name', 'age',' tel', 'isonly']) # print dictionary all values > print (python_obj.values ()) dict_values ([' Xiaoming', 30, ['8888', '1351111111'], True])

File operation:

Import jsonf = open ('data.json', encoding='utf-8') content = f.read () # use the loads () method to read the file python_obj = json.loads (content) print (python_obj)

Output result:

7. Json.load ()

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

Syntax format: json.load (fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, * * kw)

File operation:

Import jsonpython_obj = json.load (open ('data.json','r')) print (python_obj) print (type (python_obj))

Output result:

The difference between json.load () and json.loads ():

Loads () passes a json string, while load () passes a file object

When using loads (), you need to read the file first in use, while load () does not

8. Summary

Whether it is dump or load, those with s are related to strings, and those without s are related to files.

III. Transfer between XML file and JSON file

A little skill commonly used in recording work

The cmd console installs third-party modules:

Pip install xmltodict1 and XML files are converted to JSON files

Create a new 1.xml file:

Tom mary love

Transcoding implementation:

Import jsonimport xmltodictdef xml_to_json (xml_str): "parse is the xml parser. The parameter requires: param xml_str: xml string: return: json string" xml_parse = xmltodict.parse (xml_str) # json library dumps () converts dict to json format, loads () converts json to dict format. " The ident=1 of # dumps () method, formatted json json_str = json.dumps (xml_parse, indent=1) return json_strXML_PATH ='. / 1.xml' # xml file path with open (XML_PATH,'r') as f: xmlfile = f.read () with open (XML_PATH [:-3] + 'json', 'w') as newfile: newfile.write (xml_to_json (xmlfile))

Output result (generate json file):

2. Convert JSON files to XML files

Create a new test.json file:

{"student": {"course": {"name": "math", "score": "90"}, "info": {"sex": "male", "name": "name"}, "stid": "10213"}}

Transcoding implementation:

Import xmltodictimport jsondef json_to_xml (python_dict): "" unparse () json of xmltodict library to xml: param python_dict: dictionary object of python: return: xml string "xml_str = xmltodict.unparse (python_dict) return xml_strJSON_PATH ='. / test.json' # json file path with open (JSON_PATH 'r') as f: jsonfile = f.read () python_dict = json.loads (jsonfile) # converts the json string to the python dictionary object with open (JSON_PATH [:-4] + 'xml',') as newfile: newfile.write (json_to_xml (python_dict))

Output result (generate xml file):

After reading this, the article "how to use Python's json standard library" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it to understand it. If you want to know more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report