2017-03-08 12 views
7

json-string을 python 개체로 변환해야합니다. 객체 란 다음과 같은 "새로운"python3 객체를 의미합니다.json을 개체로 변환하는 방법?

class MyClass(object): 

예를 들어 jsonpickle 설명서에서 여러 가지 도움말을 발견했습니다. 하지만 내가 찾은 것은 객체를 json으로 먼저 변환 한 후 튜토리얼로 변환 한 후 거꾸로 변환하는 것입니다.

json-string을 Rest-API으로 변환하고 싶습니다.

그것은 jsonpickle 내 수업이 변환 할 수 없습니다 것을 나에게 매우 분명
TypeError: the JSON object must be str, bytes or bytearray, not 'method' 

(목표, 경기 :

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) 

이 결과 : 여기

내가 지금까지 한 일이다) 왜냐하면 나는 어떤 클래스에서 출력을 변환해야하는지 jsonpickle에게 말하지 않기 때문이다. 문제는 jsonpickle에게 객체의 JSON을 Match 유형으로 변환하는 방법을 알려주지 못한다는 것입니다. 목표 목록이 List<Goal> 유형이어야한다고 어떻게 알 수 있습니까? 위의

obj = jsonpickle.decode(result.content) # NOTE: `.content`, not `.json` 

obj = result.json() 

그러나 아무도 당신에게 당신이 원하는 것을() (dicitonary하지 파이썬 객체)를 제공하지 않습니다 :

+0

'OBJ = jsonpickle.decode (result.content)는'=> 이렇게하면 사전을 제공 할 것입니다. – falsetru

+0

'obj = result.json()'도 사전을 줄 것입니다. – falsetru

답변

6

다음 줄 당신에게 사전을 제공 할 것입니다. URL에서 JSON이 jsonpickle.encode로 인코딩되지 않기 때문에 - 생성 된 JSON에 정보를 추가 whcih ({"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} 

, object_hook와 json.loads를 사용하여, 당신은 dic["Goals"][0]["GoalGetterName"]dic.Goals.[0].GoalGetterName을 선호 즉 :

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 
+0

감사합니다. dic을 통한 마법의 문자열 액세스가 마음에 들지 않기 때문에, dic을 객체로 변환하는 클래스 메소드를 사용하는 것이 가장 좋습니다. – Sebi

+0

@ Sebi, 왜 당신은 객체를 객체로 변환합니까? 방금 Python을 사용할 때 변환하지 않고 사전/목록 /을 사용했습니다. (나는 그것이 마법의 문자열 접근이라고 생각하지 않는다 ;;;) – falsetru

+0

@Sebi, 나는 이것을 사용하지 않았지만 이것을 확인해 보았다 : http://jsonmodels.readthedocs.io/en/latest/ – falsetru

5

를 수행 요 이런 뜻인가요? 인쇄

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) 

:

1234 
[Finished in 0.4s] 
+0

좋은 접근 덕분에 :) – Sebi

+0

당신은 환영합니다 :) – Den1al