简体   繁体   English

python:通过网络发送列表/字典

[英]python: send a list/dict over network

I'm looking for an easy way of packing/unpacking data structures for sending over the network: 我正在寻找一种简单的方法来打包/解包数据结构,以便通过网络发送:

on client just before sending: 在发送前的客户端上:

a = ((1,2),(11,22,),(111,222))
message = pack(a)

and then on server: 然后在服务器上:

a = unpack(message)

Is there a library that could do pack/unpack magic? 有没有可以打包/解压缩魔法的库? Thanks in advance 提前致谢

Looks like JSON might fit the bill. 看起来JSON可能符合要求。 It's simple, and it's in the Python standard library . 它很简单, 它在Python标准库中

It might not be too happy about the tuples, though: 但是对于元组可能不太高兴:

>>> import json
>>> a = ((1,2),(11,22,),(111,222))
>>> print a
((1, 2), (11, 22), (111, 222))
>>> message = json.dumps(a)
>>> message
'[[1, 2], [11, 22], [111, 222]]'
>>> b = json.loads(message)
>>> b
[[1, 2], [11, 22], [111, 222]]

Whether or not that's a problem is for you to decide. 这是一个问题是由你来决定的。

See pickle - Python object serialization: 请参阅pickle - Python对象序列化:

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. pickle模块实现了一个基本但强大的算法,用于序列化和反序列化Python对象结构。 “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. “Pickling”是将Python对象层次结构转换为字节流的过程,“unpickling”是反向操作,从而将字节流转换回对象层次结构。 Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”. 酸洗(和去除斑点)或者称为“序列化”,“编组”或“扁平化”,然而,为了避免混淆,这里使用的术语是“酸洗”和“去除”。

ast.literal_eval() preserves tuples: ast.literal_eval()保留元组:

>>> a = ((1,2),(11,22,),(111,222))
>>> s = repr(a)
>>> import ast
>>> ast.literal_eval(s)
((1, 2), (11, 22), (111, 222))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM