2017-03-08 45 views
7

Bir json dizesini python nesnesine dönüştürmem gerekiyor. Nesnenin derken demek gibi "yeni" python3 nesnesi: Ben jsonpickle belgelere örneğin birkaç yardım buldumJson nesnesine nasıl dönüştürülür?

class MyClass(object): 

. Ama bulduğum her şey nesneyi json'a dönüştüren ve sonradan geriye dönüş yapan öğreticilerdir.

Bir json dizesini Rest-API'dan dönüştürmek istiyorum.

Bu jsonpickle Derslerimi nasıl çeviririm olamaz bana göre gayet açıktır
TypeError: the JSON object must be str, bytes or bytearray, not 'method' 

(Hedef, Match:

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) 

Bu sonuçlanır: Burada

şimdiye kadar yapmış budur), çünkü jsonpickle'a hangi sınıfta çıktı dönüştürüleceğini söylemiyorum. Sorun Jsonpickle'a JSON'u nesne türündeki nesneye dönüştürmeyi nasıl söyleyeceğimi bilmiyorum. Ve hedefler listesinin List<Goal> türünde olması gerektiğini nasıl anlarım? Yukarıdakilerin

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

obj = result.json() 

Ama hiçbiri size ne istediğinizi() (dicitonary değil piton nesne) verecektir:

+0

'obj = jsonpickle.decode (result.content)' => Bu size bir sözlük verecektir. – falsetru

+0

'obj = result.json()' ayrıca bir sözlük de verecektir. – falsetru

cevap

6

aşağıdaki satırları size bir sözlük verecektir. url'den json jsonpickle.encode ile kodlanmış nedeniyle - Oluşturulan bir json ek bilgi eklemek whcih ({"py/object": "__main__.Goal", ....} gibi bir şey) Eğer bir sözlük değildir gerçek bir Python nesne istiyorsanız


>>> 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 ile json.loads kullanmak, sen dic["Goals"][0]["GoalGetterName"] için dic.Goals.[0].GoalGetterName tercih yani:

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

Tamam çok teşekkür ederim. Çünkü dic üzerinden sihirli string erişimini beğenmediğim için, bir dic'i bir nesneye dönüştüren bir sınıf metodu kullanmak en iyi yöntem midir? – Sebi

+0

@Sebi, Neden bu kuralı bir nesneye dönüştürüyorsunuz? Ben sadece Python'u kullanırken çevirmeden sözlük/liste/... kullandım. (Bunun bir sihirli dize erişimi olduğunu düşünmüyorum ;;;) – falsetru

+0

@Sebi, bunu kullanmadım, ama şuna bak: http://jsonmodels.readthedocs.io/en/latest/ – falsetru

5

mı yo Böyle bir şey mi demek istiyorsun? yazdırır

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

İyi yaklaşımlar teşekkürler :) – Sebi

+0

Rica ederim :) – Den1al