2009-01-25 110 views
0

Possible Duplicate:
Converting XML to JSON using Python?如何將XML轉換成JSON在Python

我導入XML飼料,並試圖將其轉換成JSON輸出。我得到這個錯誤:

TypeError: <xml.dom.minidom.Document instance at 0x72787d8> is not JSON serializable

不幸的是,我知道旁邊沒有關於Python。我正在Google App Engine上開發這個功能。我可以使用一些幫助,因爲我那小小的2小時黑客攻入了第三天。

XML數據:

<?xml version="1.0" ?><eveapi version="2"> 
    <currentTime>2009-01-25 15:03:27</currentTime> 
    <result> 
    <rowset columns="name,characterID,corporationName,corporationID" key="characterID" name="characters"> 
     <row characterID="999999" corporationID="999999" corporationName="filler data" name="someName"/> 
    </rowset> 
    </result> 
    <cachedUntil>2009-01-25 15:04:55</cachedUntil> 

</eveapi> 

我的代碼:

class doproxy(webapp.RequestHandler): 
def get(self): 
    apiurl = 'http://api.eve-online.com' 

    path = self.request.get('path'); 
    type = self.request.get('type'); 
    args = '&'+self.request.get('args'); 

    #assemble api url 
    url = apiurl+path 

    #do GET request  
    if type == 'get': 
     result = urlfetch.fetch(url,'','get'); 

    #do POST request 
    if type == 'post': 
     result = urlfetch.fetch(url,args,'post'); 

    if result.status_code == 200:    
     dom = minidom.parseString(result.content) #.encode("utf-8")) 
     dom2json = simplejson.dump(dom,"utf-8") 
+0

爲什麼這會被投票?是的,OP對於Python和編碼來說絕對是新的,但最快的學習方法是提出這樣的問題。 – David 2009-01-25 15:57:56

+0

我相信這個問題的寫法會導致下調。 – nosklo 2009-01-25 16:50:57

回答

8

I'm quickly coming to the opinion that Python is potentially a great language, but that none of its users know how to actually document anything in a clear and concise way.

這個問題的態度是不會幫助這些相同的Python用戶得到答案。

正如this related question的回答中所述,XML和JSON之間沒有1對1的對應關係,所以轉換不能自動完成。

the documentation for simplejson你可以找到它能夠序列化的類型列表,它們基本上是本地Python類型(dict,list,unicode,int,float,True/False,None)。

因此,您必須創建一個僅包含這些類型的Python數據結構,然後您將該數據結構發送給simplejson.dump()