search
HomeBackend DevelopmentPython TutorialIn-memory data serialization example

In-memory data serialization example

Jul 23, 2017 am 10:07 AM
javascriptjsonpickle

1. Purpose

We need to serialize the data in memory, that is, when writing to a file, the type written can only be a string or binary type. But if we want to serialize more complex data types, such as lists, dictionaries or functions, we have to use json or pickle.

2. json serialization

1. Serialization of dumps and deserialization of loads

dumps converts the data type into a string

import json

info = {
    'name': 'The Count of Monte Cristo',
    'type': 'Movie'
}

data = json.dumps(info)
print(data)
print(type(data))

# 输出
{"name": "The Count of Monte Cristo", "type": "Movie"}
<class &#39;str&#39;>

loads converts the string into a data type

import json

get_info = json.loads(data)
print(get_info[&#39;name&#39;])
print(get_info)
print(type(get_info))

#输出
The Count of Monte Cristo
{&#39;name&#39;: &#39;The Count of Monte Cristo&#39;, &#39;type&#39;: &#39;Movie&#39;}
<class &#39;dict&#39;> 

2.dump serialization and load deserialization

dump converts the data Convert the type to a string and store it in the file

import json

info = {
    &#39;name&#39;: &#39;The Count of Monte Cristo&#39;,
    &#39;type&#39;: &#39;Movie&#39;
}

with open("test.txt", "w", encoding="utf-8") as f:
    json.dump(info, f)  # 第一个参数是内存中的数据对象,第二个参数是文件句柄

#写入文件中的内容
{"name": "The Count of Monte Cristo", "type": "Movie"}

loadConvert the file opening from a string to a data type

import json


with open("test.txt", "r", encoding="utf-8") as f:
    data_from_file = json.load(f)

print(data_from_file[&#39;name&#39;])
print(data_from_file)
print(type(data_from_file))

#输出
The Count of Monte Cristo
{&#39;name&#39;: &#39;The Count of Monte Cristo&#39;, &#39;type&#39;: &#39;Movie&#39;}
<class &#39;dict&#39;>

 

3.json serializes a function

import json

def test(name):
    print("hello,{}".format(name))

info = {
    &#39;name&#39;: &#39;The Count of Monte Cristo&#39;,
    &#39;type&#39;: &#39;Movie&#39;,
    &#39;func&#39;: test
}

data = json.dumps(info)

#输出
 File "G:/python/untitled/study6/json&pickle模块.py", line 22, in <module>
    data = json.dumps(info)
  File "G:\python\install\lib\json\__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "G:\python\install\lib\json\encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "G:\python\install\lib\json\encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "G:\python\install\lib\json\encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <function test at 0x0000021B13C57F28> is not JSON serializable

1. JSON can only handle simple data types, such as dictionaries, lists, strings, etc. It cannot handle complex data types such as functions.

2, json is common to all languages, and all languages ​​support json. If we need python to interact with other languages ​​for data, then use json format

 

3. Pickle serialization

The usage of pickle is the same as above, but the data type after pickle serialization is binary, and pickle can only be used in python use.

1.dumps && loads

import pickle


def test(name):
    print("hello,{}".format(name))

info = {
    &#39;name&#39;: &#39;The Count of Monte Cristo&#39;,
    &#39;type&#39;: &#39;Movie&#39;,
    &#39;func&#39;: test
}

data = pickle.dumps(info)
print(data)
print(type(data))

#输出
b&#39;\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x19\x00\x00\x00The Count of Monte Cristoq\x02X\x04\x00\x00\x00typeq\x03X\x05\x00\x00\x00Movieq\x04X\x04\x00\x00\x00funcq\x05c__main__\ntest\nq\x06u.&#39;

<class &#39;bytes&#39;>

import pickle

get_data = pickle.loads(data)
get_data[&#39;func&#39;](&#39;cat&#39;)
print(get_data)

#输出
hello,cat
{&#39;name&#39;: &#39;The Count of Monte Cristo&#39;, &#39;type&#39;: &#39;Movie&#39;, &#39;func&#39;: <function test at 0x00000235350A7F28>}

 

2. dump && load

import pickle


def test(name):
    print("hello,{}".format(name))

info = {
    &#39;name&#39;: &#39;The Count of Monte Cristo&#39;,
    &#39;type&#39;: &#39;Movie&#39;,
    &#39;func&#39;: test
}

with open(&#39;test.txt&#39;, &#39;wb&#39;) as f:
    pickle.dump(info, f)

# 写入test.txt文件中的内容

�}q (X   typeqX   MovieqX   funcqc__main__
test
qX   nameqX   The Count of Monte Cristoqu.

 

import pickle

with open(&#39;test.txt&#39;, &#39;rb&#39;) as f:
    get_data = pickle.load(f)
print(get_data)

# 输出

{&#39;name&#39;: &#39;The Count of Monte Cristo&#39;, &#39;func&#39;: <function test at 0x000001BA2AB4D510>, &#39;type&#39;: &#39;Movie&#39;}

 

Summary:

  • JSON values ​​support simple data types, and pickle supports all data types.

  • pickle can only support serialization and deserialization of python itself, and cannot be used for data interaction with other languages, while json can.

  • pickle serializes the entire data object, so when deserializing a function, the logic in the function body changes and follows the original function body.

The above is the detailed content of In-memory data serialization example. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

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

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

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.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

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

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function