如何将json转换为对象?
I need to convert a json-string to python object. By object I mean "new" python3 object like:
我需要将json-string转换为python对象。按对象我的意思是“新”python3对象,如:
class MyClass(object):
I found several help for example on jsonpickle documentation. But all I found are tutorials which convert object to json first and after this convert backwards.
我在jsonpickle文档中找到了一些帮助。但我发现的所有内容都是将对象首先转换为json并在此转换后向后转换的教程。
I want to convert a json-string from a Rest-API.
我想从Rest-API转换json-string。
Here is what I have done so far:
这是我到目前为止所做的:
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)
This results in:
这导致:
TypeError: the JSON object must be str, bytes or bytearray, not 'method'
It's quite clear to me that jsonpickle can't convert this to my classes (Goal, Match), because I don't tell jsonpickle in which class the output should be converted. The problem is I don't know how to tell jsonpickle to convert the JSON in object from type Match? And how can I tell that the list of goals should be of type List<Goal>
?
我很清楚,jsonpickle无法将其转换为我的类(目标,匹配),因为我不告诉jsonpickle应在哪个类中转换输出。问题是我不知道如何告诉jsonpickle从对象类型转换对象中的JSON?我怎么能告诉目标列表应该是List
2 个解决方案
#1
6
The following lines will give you a dictionary:
以下几行将为您提供一个字典:
obj = jsonpickle.decode(result.content) # NOTE: `.content`, not `.json`
obj = result.json()
But none of above will give you what you want (python object (not dicitonary)). because the json from the url is not encoded with jsonpickle.encode
- whcih add additional information to a generated json (something like {"py/object": "__main__.Goal", ....}
)
但上面没有一个能给你你想要的东西(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}
If you want an actual Python object which is not a dictionary, i.e. you prefer dic.Goals.[0].GoalGetterName
to dic["Goals"][0]["GoalGetterName"]
, use json.loads
with object_hook:
如果你想要一个不是字典的实际Python对象,即你更喜欢dic.Goals。[0] .GoalGetterName到dic [“Goals”] [0] [“GoalGetterName”],请使用带有object_hook的json.loads:
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
更多相关文章
- Python 全栈开发七 面向对象
- Python可执行对象——exec、eval、compile
- python-selenium-定位一组对象
- AttributeError:'Flask'对象没有属性'login_manager' - Login_Ma
- 在save方法中创建两个对象
- 'str'对象不能解释为groupby上的整数
- Python 面相对象 —— 类的三大成员
- Python_面向对象_单例模式
- 即使我返回2个变量,对象也不可迭代?