


This article brings you an introduction to the usage of JSON and pickle under Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1: Introduction
(1)JSON (JavaScript Object Notation) is a lightweight (XML heavyweight) data exchange format.
is a rule customized for data exchange, based on a subset of ECMAScript.
(2)JSON is a data format!
String is the representation of JSON. (A string that conforms to JSON format is called a JSON string)
(3) The json module can be used in Python3 to encode and decode JSON data. It contains two functions:
json.dumps() : Encode the data.
json.loads(): Decode the data.
(4)The advantages of JSON are: easy to read, easy to parse, high network transmission efficiency, cross-language data exchange
2: Python encoding to JSON type conversion corresponding table:
_______________________________________________ | python | JSON | ------------------------------------------------- | dict | object | ------------------------------------------------- | list,tuple | array | ------------------------------------------------- | str | string | ------------------------------------------------- | int,float,Enums | number | ------------------------------------------------- | True,False,None | true,false,null | -------------------------------------------------
Three: If you want to process files instead of strings, you can use
json.dump()
json.load()
Four: Use Pickle serializes and deserializes data
(1) method:
pickle.dump()
pickle.load()
pickle.dumps()
pickle.loads ()
(2) Data type:
All native types supported by python: boolean, integer, floating point number, complex number, string, byte, None.
Lists, tuples, dictionaries and sets composed of any primitive type.
Functions, classes, instances of classes
5: The difference between JSON and pickle
The purpose of JSON serialization and deserialization is to convert Python data types into JSON standard types ,
Or convert JSON type data to python data type to achieve data exchange between different languages!
pickle: If you want to save a piece of data during the running of the program, reuse it or send it to others, you can use this method
to write the data to a file, supporting all data types!
import json import pickle # ----------------------------------------------# # 反序列化 # ----------------------------------------------# # object json_str = '{"name":"qiyue", "age":18}' # JSON字符串 student = json.loads(json_str) # JSON对象转换为字典 print(student) print(json_str) print(type(student)) # object json_str1 = '[{"name":"qiyue", "age":18, "flag":false}, ' \ '{"name":"qiyue", "age":18}]' # JSON字符串 student1 = json.loads(json_str1) # JSON对象转换为字典 print(type(student1), student1) print(student1[0]) # ----------------------------------------------# # 序列化 # ----------------------------------------------# student2 = [ {"name": "qiyue", "age": 18, "flag": False}, {"name": "qiyue", "age": 18} ] json_str1 = json.dumps(student2) # 转换为字符串后可以利用正则表达式处理字符串 print(type(json_str1), json_str1) # ----------------------------------------------# # 处理的是文件 # ----------------------------------------------# # 将数据写入文件 student3 = [ {"name": "qiyue", "age": 18, "flag": False}, {"name": "qiyue", "age": 18} ] with open('data.json', 'w') as f: json.dump(student3, f) # 读取数据 with open('data.json', 'r') as f: data = json.load(f) # dumps(object)将对象序列化 list_a = ["English", "Math", "Chinese"] list_b = pickle.dumps(list_a) # 序列化数据 print(list_a) print(list_b) # loads(object)将对象原样恢复,并且对象类型也恢复原来的格式 list_c = pickle.loads(list_b) print(list_c) # dumps(object,file)将对象序列化后存储到文件中 group1 = ("baidu", "wen", "qingtian") f1 = open('group.txt', 'wb') pickle.dump(group1, f1, True) f1.close() # load(object, file)将文件中的信息恢复 f2 = open('group.txt', 'rb') t = pickle.load(f2) f2.close() print(t)
The above is the detailed content of Introduction to the usage of JSON and pickle under Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use
