English 中文(简体)
• 如何将一组人编成序列?
原标题:How to JSON serialize sets?

我有一份<<<>条码>,其中载有<条码>-hash__和<条码>_eq_的物体,以便在收集过程中不列入任何重复内容。

我需要把这一结果编码编码为set,但甚至通过一个空洞的<代码>>>>>>至json.dumps。 这种方法产生<代码>TypeError。

  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 178, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: set([]) is not JSON serializable

我知道,我可以扩大<代码>json。 缩略语 在缺省方法中,我是否应当从“<>条码/代码”的数值中选取一个字句子,然后回去。 理想的情况是,我想使缺省方法能够处理最初的焦炭cho上的所有数据类型(如果用Mongo作为数据来源,日期似乎也会产生这一错误)。

欢迎对正确方向的任何暗示。

http://www.un.org。

感谢答案! 或许 我本来应该更加准确。

我利用(并引述)这里的答复,以了解正在翻译的<条码><>>><>>>> /代码”的局限性,但内部钥匙也是一个问题。

<>t中的物体是折成<>code__dict__/code>的复合物体,但本身也可能含有其财产价值,这些价值可能不符合json encoder的基本类型。

有许多不同的类型加入<>条码/代码>,而该条码基本计算了该实体独一无二的补贴,但本着NSQL的真正精神,没有确切说明该儿童物体的特性。

其中一个物体可能包含<代码>starts的日值,而另一个物体可能还有其他一些图示,其中不包括不含“非强制性”物体的钥匙。

That is why the only solution I could think of was to extend the JSONEncoder to replace the default method to turn on different cases - but I m not sure how to go about this and the documentation is ambiguous. In nested objects, does the value returned from default go by key, or is it just a generic include/discard that looks at the whole object? How does that method accommodate nested values? I ve looked through previous questions and can t seem to find the best approach to case-specific encoding (which unfortunately seems like what I m going to need to do here).

最佳回答
问题回答

您可以形成一种习俗,即回归<条码>。 查阅<代码>的。 例如:

import json
class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj)

data_str = json.dumps(set([1,2,3,4,5]), cls=SetEncoder)
print(data_str)
# Output:  [1, 2, 3, 4, 5] 

你也可以这样发现其他类型。 如果你需要保留该清单实际上是一套清单,那么你可以采用一种惯例编码。 诸如<代码>return{ 类型: 编号:list(obj)}等内容可能有效。

To illustrate nested types, consider serializing this:

class Something(object):
    pass
json.dumps(set([1,2,3,4,5,Something()]), cls=SetEncoder)

造成以下错误:

TypeError: <__main__.Something object at 0x1691c50> is not JSON serializable

这表明,遗体将采用list结果,并改称其子女的序列器。 为了增加多种类型的定制序列器,你可以这样做:

class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        if isinstance(obj, Something):
            return  CustomSomethingRepresentation 
        return json.JSONEncoder.default(self, obj)
 
data_str = json.dumps(set([1,2,3,4,5,Something()]), cls=SetEncoder)
print(data_str)
# Output:  [1, 2, 3, 4, 5, "CustomSomethingRepresentation"] 

您不必为提供<代码>default的方法而做一门定制,这可以作为关键词加以通过:

import json

def serialize_sets(obj):
    if isinstance(obj, set):
        return list(obj)

    return obj

json_str = json.dumps(set([1,2,3]), default=serialize_sets)
print(json_str)

参看[1, 2, 3], 载于所有辅助文本。

If you know for sure that the only non-serializable data will be sets, there s a very simple (and dirty) solution:

json.dumps({"Hello World": {1, 2}}, default=tuple)

只有非消耗性数据才能按照default的功能处理,因此,只有<代码>>>>>>>>>>将转换成<>tuple。

页: 1 Hettinger s Solutions to python 3. 。

这里的变化是:

  • unicode disappeared
  • updated the call to the parents default with super()
  • using base64 to serialize the bytes type into str (because it seems that bytes in python 3 can t be converted to JSON)
from decimal import Decimal
from base64 import b64encode, b64decode
from json import dumps, loads, JSONEncoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
            return super().default(obj)
        return { _python_object : b64encode(pickle.dumps(obj)).decode( utf-8 )}

def as_python_object(dct):
    if  _python_object  in dct:
        return pickle.loads(b64decode(dct[ _python_object ].encode( utf-8 )))
    return dct

data = [1,2,3, set([ knights ,  who ,  say ,  ni ]), { key : value }, Decimal( 3.14 )]
j = dumps(data, cls=PythonObjectEncoder)
print(loads(j, object_hook=as_python_object))
# prints: [1, 2, 3, { knights ,  who ,  say ,  ni }, { key :  value }, Decimal( 3.14 )]

如果你需要迅速倾销,不希望执行习俗。 您可以采取以下措施:

json_string = json.dumps(data, iterable_as_array=True)

这将把所有设备(和其他可变设备)转化为阵列。 诚然,当你把JSON带回来时,这些田地将保持阵列。 如果你想保留这些类型,你需要写照。

Also make sure to have simplejson installed and required.
You can find it on PyPi.

只有JSON有字典、清单和原始物体类型(打字、铺设、包裹)。

The Shortened edition of @AnttiHaapala:

json.dumps(dict_with_sets, default=lambda x: list(x) if isinstance(x, set) else x)

如果你只需要编码系统,而不是普通物体,并且希望能够方便人类阅读,那么,可以使用一个简便版本的雷蒙·赫特赫特回答:

import json
import collections

class JSONSetEncoder(json.JSONEncoder):
    """Use with json.dumps to allow Python sets to be encoded to JSON

    Example
    -------

    import json

    data = dict(aset=set([1,2,3]))

    encoded = json.dumps(data, cls=JSONSetEncoder)
    decoded = json.loads(encoded, object_hook=json_as_python_set)
    assert data == decoded     # Should assert successfully

    Any object that is matched by isinstance(obj, collections.Set) will
    be encoded, but the decoded value will always be a normal Python set.

    """

    def default(self, obj):
        if isinstance(obj, collections.Set):
            return dict(_set_object=list(obj))
        else:
            return json.JSONEncoder.default(self, obj)

def json_as_python_set(dct):
    """Decode json { _set_object : [1,2,3]} to set([1,2,3])

    Example
    -------
    decoded = json.loads(encoded, object_hook=json_as_python_set)

    Also see :class:`JSONSetEncoder`

    """
    if  _set_object  in dct:
        return set(dct[ _set_object ])
    return dct
>>> import json
>>> set_object = set([1,2,3,4])
>>> json.dumps(list(set_object))
 [1, 2, 3, 4] 

One shortcoming of the accepted solution is that its output is very python specific. I.e. its raw json output cannot be observed by a human or loaded by another language (e.g. javascript). example:

db = {
        "a": [ 44, set((4,5,6)) ],
        "b": [ 55, set((4,3,2)) ]
        }

j = dumps(db, cls=PythonObjectEncoder)
print(j)

请你:

{"a": [44, {"_python_object": "gANjYnVpbHRpbnMKc2V0CnEAXXEBKEsESwVLBmWFcQJScQMu"}], "b": [55, {"_python_object": "gANjYnVpbHRpbnMKc2V0CnEAXXEBKEsCSwNLBGWFcQJScQMu"}]}

我可以提出一种解决办法,将这套文件降级为载有出路清单的法令,并在使用同一编码装入假日时重新排入一个清单,从而维护可观测性和语言学:

from decimal import Decimal
from base64 import b64encode, b64decode
from json import dumps, loads, JSONEncoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
            return super().default(obj)
        elif isinstance(obj, set):
            return {"__set__": list(obj)}
        return { _python_object : b64encode(pickle.dumps(obj)).decode( utf-8 )}

def as_python_object(dct):
    if  __set__  in dct:
        return set(dct[ __set__ ])
    elif  _python_object  in dct:
        return pickle.loads(b64decode(dct[ _python_object ].encode( utf-8 )))
    return dct

db = {
        "a": [ 44, set((4,5,6)) ],
        "b": [ 55, set((4,3,2)) ]
        }

j = dumps(db, cls=PythonObjectEncoder)
print(j)
ob = loads(j)
print(ob["a"])

你们:

{"a": [44, {"__set__": [4, 5, 6]}], "b": [55, {"__set__": [2, 3, 4]}]}
[44, { __set__ : [4, 5, 6]}]

<>>>>,序列化含有关键<代码>内容的词典”__ __set__>将打破这一机制。 www.un.org/spanish/ecosoc 现在已成为一个保留<代码> 字标/代码>的关键。 显然可以自由使用另一个更深层混淆的钥匙。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签