我需要将json-string转换为python对象。按对象我的意思是“新”python3对象,如:
class MyClass(object):
我在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)
这导致:
TypeError: the JSON object must be str, bytes or bytearray, not 'method'
我很清楚jsonpickle无法将其转换为我的类(目标,匹配),因为我没有告诉jsonpickle应该在哪个类中转换输出。问题是我不知道如何告诉jsonpickle从对象类型转换对象中的JSON?我如何判断目标列表应该是List<Goal>
类型?
答案 0 :(得分:6)
以下几行将为您提供字典:
obj = jsonpickle.decode(result.content) # NOTE: `.content`, not `.json`
obj = result.json()
但上面没有一个能给你你想要的东西(python对象(不是dicitonary))。因为来自url的json没有用jsonpickle.encode
编码 - whcih向生成的json添加其他信息(类似{"py/object": "__main__.Goal", ....}
)
>>> import jsonpickle
>>> class Goal(object):
... def __init__(self):
... self.GoaldID = -1
... self.IsPenalty = False
...
>>> jsonpickle.encode(Goal())
'{"py/object": "__main__.Goal", "IsPenalty": false, "GoaldID": -1}'
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# JSON encoded with jsonpickle.encode (default unpicklable=True)
# => additional python class information attached
# => can be decoded back to Python object
>>> jsonpickle.decode(jsonpickle.encode(Goal()))
<__main__.Goal object at 0x10af0e510>
>>> jsonpickle.encode(Goal(), unpicklable=False)
'{"IsPenalty": false, "GoaldID": -1}'
# with unpicklable=False (similar output with json.dumps(..))
# => no python class information attached
# => cannot be decoded back to Python object, but a dict
>>> jsonpickle.decode(jsonpickle.encode(Goal(), unpicklable=False))
{'IsPenalty': False, 'GoaldID': -1}
如果你想要一个不是字典的实际Python对象,即你更喜欢dic.Goals.[0].GoalGetterName
到dic["Goals"][0]["GoalGetterName"]
,请使用json.loads
和object_hook:
import json
import types
import requests
url = "https://www.openligadb.de/api/getmatchdata/39738"
result = requests.get(url)
data = json.loads(result.content, object_hook=lambda d: types.SimpleNamespace(**d))
# OR data = result.json(object_hook=lambda d: types.SimpleNamespace(**d))
goal_getter = data.Goals[0].GoalGetterName
# You get `types.SimpleNamespace` objects in place of dictionaries
答案 1 :(得分:5)
你的意思是这样吗?
hostReady.emit();
打印:
import json
class JsonObject(object):
def __init__(self, json_content):
data = json.loads(json_content)
for key, value in data.items():
self.__dict__[key] = value
jo = JsonObject("{\"key1\":1234,\"key2\":\"Hello World\"}")
print(jo.key1)
答案 2 :(得分:0)
使用最新的python版本的一种干净方法可能是使用marshmallow-dataclass:
from dataclasses import field
from marshmallow_dataclass import dataclass
from typing import List
@dataclass
class Goal:
GoaldID: int = field(default=-1)
IsPenalty: bool = field(default=False)
@dataclass
class Match:
Goals: List[Goal] = field(default_factory=lambda: [])
my_match, _ = Match.Schema().load(result.json())