跳转到主要内容

带有类型信息的JSON解码器和编码器。

项目描述

StrongJson

PyPI Build Status Binder codecov

更忠实的Python json编码/解码器。

安装

pip install strong_json

或直接从此仓库安装

pip install git+git://github.com/piti118/strong-json.git

功能

除了标准的json.dumps/loads之外,此模块还提供以下附加行为。

  • 支持自定义类(可通过ToJsonable接口重写)。

    • class User:
          def __init__(self, first, last):
              self.first = first
              self.last = last
      
  • 保留类型信息。

    • User('f', 'l') -> {"__type__": "User", "first":"f", "last":"l"}
  • 更忠实的字典dumps/loads

    • 编码时将字典视为OrderedDictionary。请参阅Python 3.6 发布说明
      • {'a':'b', 'c':'d'} ->
        {
            "__type__": "dict",
            "__data__": [
                {"key": "a", "value": "b"},
                {"key": "c", "value": "d"}
            ]
        }
        
      • 解码器将接受传统格式({'a':'b','c':'d'})和上述格式。
    • 允许任何可哈希对象作为键
      • {User('f', 'l'): 1, User('a','b'):2} ->
        {
            "__type__": "dict",
            "__data__": [
                {
                    "key": {"__type__": "User", "first": "f", "last":"l"}, 
                    "value": 1
                },
                {
                    "key": {"__type__": "User", "first": "a", "last":"b"}, 
                    "value": 2
                }
            ]
        }        
        
  • 区分元组与列表

    • [1,2,3] -> [1,2,3]
    • (1,2,3) -> {"__type__":"tuple", "__data__":[1,2,3]}
  • 通过class_map自定义类解码器白名单

    • from strong_json import StrongJson
      s = {'__type__': 'User', 'first':'f', 'last':'l'}
      class_map = {'User', User}
      custom_json = StrongJson(class_map=class_map)
      custom_json.from_json(s)
      
    • 默认情况下,strong json将所有参数通过名称传递给构造函数。
    • 您也可以重写StrongJson或实现接口FromJsonable以自定义解码器。
    • 您还可以使用 strong_json.ClassMapBuilder 来节省一些输入。
  • 支持日期和时间。

    • datetime.date(2019,8,23) ->
    {
        "__type__": "date", 
        "year": 2019, 
        "month": 8, 
        "day": 23
    }
    
  • 支持枚举。

    • from enum import Enum
      class Color(Enum):
        RED='redd'
        BLUE='blueee'
      strong_json.to_json(Color.RED)
      
      ->
      {"__type__": "Color", "__data__":"RED"}
      
  • 支持 numpy 和 pandas。 (通过 to_dicttolist)

  • nan, inf, -inf 以字典形式输出,例如:{"__type__":"float", "__data__":"nan"}

基本用法

Binder

从对象到 JSON

内置对象

from strong_json import strong_json
obj = {'a': [1,2,3], 'b':[2,3,4]}
s = strong_json.to_json(obj)

# if you want indentation you could do
s_indent = strong_json.to_json(obj, indent=2)

自定义类

SimpleClass

自定义类直接使用

from strong_json import strong_json

class SimpleClass:
    def __init__(self, msg):
        self.msg = msg

obj = SimpleClass('hello')
s = strong_json.to_json(object)

生成如下格式的 JSON

{
  "__type__": "SimpleClass",
  "msg": "hello"
}

自定义编码器。

如果您不喜欢默认的类编码器,可以通过实现 ToJsonable 接口创建新的编码器。

from strong_json import strong_json, ToJsonable

class User(ToJsonable):
    def __init__(self, first, last):
        self.first = first
        self.last = last

    # this is where the magic happens.
    def to_json_dict(self, encoder: StrongJson) -> Dict[str, JSONPrimitive]:
        return {
            '__type__': 'User',
            'first': encoder.to_json_dict(self.first),
            'last': encoder.to_json_dict(self.last),
            'full_name': encoder.to_json_dict(f"{self.first} {self.last}")
        }

obj = User('hello', 'world')
s = strong_json.to_json(object)

生成如下格式的 JSON

{
  "__type__": "User",
  "first": "hello",
  "last": "world",
  "full_name": "hello_world"
}

从 JSON 到对象

内置对象

from strong_json import strong_json
s = """{"a": "b", "c":"d"}"""
obj = strong_json.from_json(s)

自定义类

from strong_json import StrongJson

class User: # it doesn't have to be ToJsonable
    def __init__(self, first, last):
        self.first = first
        self.last = last

s = """
{
    "__type__": "User",
    "first": "hello",
    "last": "world"
}
"""
class_map = {'User': User}
custom_json = StrongJson(class_map=class_map)
obj = custom_json.to_json(s, class_map)

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源代码分发

本发布版本没有提供源代码分发文件。请参阅 生成分发存档的教程

构建分发

strong_json-1.0.11-py3-none-any.whl (9.1 kB 查看哈希值)

上传时间 Python 3

由以下组织支持