我有以下简单的方法使用jsonpickle将python对象写入文件:
def json_serialize(obj, filename, use_jsonpickle=True):
f = open(filename, 'w')
if use_jsonpickle:
import jsonpickle
json_obj = jsonpickle.encode(obj)
f.write(json_obj)
else:
simplejson.dump(obj, f)
f.close()
def json_load_file(filename, use_jsonpickle=True):
f = open(filename)
if use_jsonpickle:
import jsonpickle
json_str = f.read()
obj = jsonpickle.decode(json_str)
else:
obj = simplejson.load(f)
return obj
Run Code Online (Sandbox Code Playgroud)
问题是,无论何时我使用它们,它都会将我的对象作为字典(具有类似"py/object":"my_module.MyClassName")的字段加载回来,而不是用作生成的类型的实际Python对象json字符串.我怎么能这样做jsonpickle实际上将加载的字符串转换回对象?
用一个例子来说明这一点,请考虑以下内容:
class Foo:
def __init__(self, hello):
self.hello = hello
# make a Foo obj
obj = Foo("hello world")
obj_str = jsonpickle.encode(obj)
restored_obj = jsonpickle.decode(obj_str)
list_objects = [restored_obj]
# We now get a list with a dictionary, …Run Code Online (Sandbox Code Playgroud) 我正在使用Flask的SQLAlchemy扩展.在使用jsonpickle 序列化我的模型(也用于数据库操作)时,我想要忽略一些特定的属性.有没有办法让我设定这些规则?
SQLAlchemy添加了一个名为_sa_instance_state该对象的属性.总之,我不希望这个字段在JSON输出中.
我正在使用 JSON 序列化器辅助函数来轻松访问字典(基本上以 JSON 形式接收)对象。
jsondict.py
"""Utilities for working with JSON and json-like structures - deeply nested Python dicts and lists
This lets us iterate over child nodes and access elements with a dot-notation.
"""
import sys
isPy3 = sys.version_info[0]==3
if isPy3:
def __alt_str__(v,enc='utf8'):
return v if isinstance(v,bytes) else v.encode(enc)
__strTypes__ = (str,bytes)
else:
__alt_str__ = unicode
__strTypes__ = (str,unicode)
class MyLocals(object):
pass
mylocals = MyLocals()
def setErrorCollect(collect):
mylocals.error_collect = collect
setErrorCollect(False)
def errorValue(x):
if isinstance(x,__strTypes__):
return repr(x) if ' …Run Code Online (Sandbox Code Playgroud) 我正在尝试腌制使用以下命令创建的嵌套字典:
collections.defaultdict(lambda: collections.defaultdict(int))
Run Code Online (Sandbox Code Playgroud)
我的简化代码是这样的:
class A:
def funA(self):
#create a dictionary and fill with values
dictionary = collections.defaultdict(lambda: collections.defaultdict(int))
...
#then pickle to save it
pickle.dump(dictionary, f)
Run Code Online (Sandbox Code Playgroud)
但是它给出了错误:
AttributeError: Can't pickle local object 'A.funA.<locals>.<lambda>'
Run Code Online (Sandbox Code Playgroud)
我打印字典后显示:
defaultdict(<function A.funA.<locals>.<lambda> at 0x7fd569dd07b8> {...}
Run Code Online (Sandbox Code Playgroud)
我尝试在该函数中使字典全局化,但错误是相同的。我很欣赏这个问题的任何解决方案或见解。谢谢!
我需要将json-string转换为python对象.按对象我的意思是"新"python3对象,如:
class MyClass(object):
Run Code Online (Sandbox Code Playgroud)
我在jsonpickle文档中找到了一些帮助.但我发现的只是教程,它首先将对象转换为json,然后向后转换.
我想从Rest-API转换json-string .
这是我到目前为止所做的:
import requests
import jsonpickle
class Goal(object):
def __init__(self):
self.GoaldID = -1
self.IsPenalty = False
class Match(object):
def __init__(self):
self.Goals = []
headers = {
"Content-Type": "application/json; charset=utf-8"
}
url = "https://www.openligadb.de/api/getmatchdata/39738"
result = requests.get(url=url, headers=headers)
obj = jsonpickle.decode(result.json)
print (obj)
Run Code Online (Sandbox Code Playgroud)
这导致:
TypeError: the JSON object must be str, bytes or bytearray, not 'method'
Run Code Online (Sandbox Code Playgroud)
我很清楚,jsonpickle无法将其转换为我的类(目标,匹配),因为我没有告诉jsonpickle应该在哪个类中转换输出.问题是我不知道如何告诉jsonpickle从对象类型转换对象中的JSON?我怎么能说出目标列表应该是类型List<Goal>?
我正在尝试保存和加载 scikit-learn 模型,但当保存和加载发生在不同的 python 版本上时遇到问题。这是我尝试过的:
使用pickle在python3中保存模型并在python2中反序列化。这适用于某些模型,如LR、SVM,但不适用于KNN。
>>> pickle.load(open("inPy3.pkl", 'rb')) #KNN model
ValueError: non-string names in Numpy dtype unpickling
Run Code Online (Sandbox Code Playgroud)另外,我尝试使用 jsonpickle 在 json 中序列化和反序列化,但出现以下错误。
data = jsonpickle.encode(lr) #lr = logisticRegression Model
jsonpickle.decode(data)
AttributeError: 'dict' object has no attribute '__name__'
Run Code Online (Sandbox Code Playgroud)另外,我想知道是否有一些实用程序可以用来将 scikit-learn 模型对象序列化和反序列化为人类可读的格式(json、xml、protobuf 等)。
在用于 JSON 序列化和反序列化的 Python 的 jsonpickle 模块的文档中,它指出
从不受信任的来源加载 JSON 字符串表示潜在的安全漏洞。jsonpickle 不尝试清理输入
但我想知道攻击者怎么可能通过 JSON 消息执行任意代码?
另外,按照文档中的建议清理输入的最佳方法是什么?我的应用程序中的 JSON 数据不值得信任(它来自发送 JSON 消息的客户端)。
我想使用 Python 的 pickle 序列化器为缺失值提供默认值。由于类很简单,默认值自然存在于类的__init__方法中。
我可以从泡菜文档中看到有__getnewargs__. 但是,这仅适用于__getnewargs__“酸洗”之前存在的情况。
有什么方法可以告诉 python pickle 始终调用构造函数而不是从未初始化的对象开始?
是否可以将日期时间转换为可读的 JSON 格式(可以从 javascript 中使用)?目前 jsonpickle 仅提供日期时间的二进制编码值。
使用 Python 和 JsonPickle,如何使用特定的大小写(例如 Camel Case、Pascal 等)序列化对象?下面的答案是手动完成的,但是寻找特定的 Jsonpickle 解决方案,因为它可以处理复杂的对象类型。
class HardwareSystem:
def __init__(self, vm_size):
self.vm_size = vm_size
self.some_other_thing = 42
self.a = 'a'
def snake_to_camel(s):
a = s.split('_')
a[0] = a[0].lower()
if len(a) > 1:
a[1:] = [u.title() for u in a[1:]]
return ''.join(a)
def serialise(obj):
return {snake_to_camel(k): v for k, v in obj.__dict__.items()}
hp = HardwareSystem('Large')
print(json.dumps(serialise(hp), indent=4, default=serialise))
Run Code Online (Sandbox Code Playgroud) jsonpickle ×10
python ×10
json ×4
pickle ×4
python-3.x ×4
python-3.6 ×2
constructor ×1
flask ×1
python-2.7 ×1
python-3.7 ×1
scikit-learn ×1
security ×1
sqlalchemy ×1