2014-02-13 65 views
1

我有下面的示例JSON條目的JSON文件:Python的。獲得嵌套的JSON值

{ 
      "title": "Test prod", 
      "leafPage": true, 
      "type": "product", 
      "product": { 
       "title": "test product", 
       "offerPrice": "$19.95", 
       "offerPriceDetails": { 
        "amount": 19.95, 
        "text": "$19.95", 
        "symbol": "$" 
       }, 
       "media": [ 
        { 
         "link": "http://www.test.com/cool.jpg", 
         "primary": true, 
         "type": "image", 
         "xpath": "/html[1]/body[1]/div[1]/div[3]/div[2]/div[1]/div[1]/div[1]/div[1]/a[1]/img[1]" 
        } 
       ], 
       "availability": true 
      }, 
      "human_language": "en", 
      "url": "http://www.test.com" 
     } 

我可以通過Python腳本張貼此對我的測試服務器完美,當我使用:

     "text": entry.get("title"), 
        "url": entry.get("url"), 
        "type": entry.get("type"), 

但是我不能讓下面的嵌套項上傳的價值觀,我該如何構建蟒蛇JSON調用get嵌套蟒蛇JSON入門?

我用盡下面沒有成功,我需要把它作爲不用彷徨,因爲有不同的領域目前在JSON文件,並出現了錯誤,而不不用彷徨電話。

    "Amount": entry.get("product"("offerPrice")) 

任何有關如何構建嵌套json條目的幫助將非常感謝。

回答

5

你需要做的:

"Amount": entry.get("product", {}).get("offerPrice") 

entry.get("product", {})返回一個產品字典(或一個空的字典如果沒有product鍵)。

+0

十分感謝,多數民衆贊成的工作!因此要獲得的產品{媒體,我可以用一個嵌套的對象:entry.get( 「產品」,{})獲得( 「媒體」,{})獲得( 「鏈接」)。? – user1461716

+0

由於媒體是然後列表:entry.get( 「產品」,{})獲得( 「媒體」,[{}])[0]獲得( 「鏈接」) –