>  기사  >  백엔드 개발  >  메모리 내 데이터 직렬화 예시

메모리 내 데이터 직렬화 예시

零下一度
零下一度원래의
2017-07-23 10:07:431535검색

1. 목적

메모리에 있는 데이터를 직렬화해야 합니다. 즉, 파일에 쓸 때 쓰는 유형은 문자열 또는 바이너리 유형만 될 수 있습니다. 그러나 목록, 사전 또는 함수와 같은 더 복잡한 데이터 유형을 직렬화하려면 json 또는 pickle을 사용해야 합니다.

2.json 직렬화

1, 직렬화 덤프 및 역직렬화 로드

dumps는 데이터 유형을 문자열로 변환

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는 문자열을 데이터 유형으로 변환

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 직렬화 및 load deserialization

dump는 데이터 유형을 문자열로 변환하여 파일에 저장합니다.

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"}

load는 파일을 열고 문자열에서 데이터 유형으로 변환합니다.

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 함수 직렬화

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은 사전, 목록, 문자열 등과 같은 간단한 데이터 유형만 처리할 수 있으며 함수와 같은 복잡한 데이터 유형은 처리할 수 없습니다.

2. json은 모든 언어에 공통입니다. 모든 언어는 json을 지원합니다. 데이터를 위해 다른 언어와 상호 작용하기 위해 Python이 필요한 경우 json 형식을 사용하세요.

 

pickle 사용법은 위와 동일하지만, pickle로 직렬화한 데이터 유형이 바이너리이고, pickle은 Python에서만 사용할 수 있습니다.

1.dumps && 로드

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.dumps && 로드

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;}
 

요약:

  • json 값은 단순 데이터 유형을 지원합니다. , 피클은 모든 데이터 유형을 지원합니다.

  • pickle은 Python 자체의 직렬화 및 역직렬화만 지원할 수 있으며 다른 언어와의 데이터 상호 작용에는 사용할 수 없지만 json은 사용할 수 있습니다.

  • pickle은 전체 데이터 객체를 직렬화하므로 함수를 역직렬화할 때 함수 본문의 논리가 변경되어 원래 함수 본문을 따릅니다.

위 내용은 메모리 내 데이터 직렬화 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.