簡體   English   中英

python:從json字符串中獲取特定值

[英]python : get specific value from json string

我需要從 Json 響應中獲取精確值,我怎樣才能獲得特定的 json 值 python ???

這是我的 Json 字符串,我需要提取Id

"window.__store__ ="{
 "listingReducer":{
    "selectedListing":{
         "id":2234588,
         "has_video":0,
         "refresh":1625551240,
         "category":6,
         "ketchen":1,
         "lift":1,
         "livings":1,
         "maid":null,
         "meter_price":null,
         "playground":null,
         "location":{
            "lat":26.378031,
            "lng":50.124866
         },
         "views":6075,
      },3

}
}

這是我的python代碼:

import json
from selenium import webdriver


jsonScript =driver.find_element_by_xpath("/html/body/script[6]")
jsonText = jsonScript.get_attribute('innerHTML')

.
.
.

json_str = json.dumps(jsonText)
resp = json.loads(json_str)
#print (resp)
print(resp[0]['listingReducer']['selectedListing']['id'])

.
.
.

這是錯誤

TypeError: string indices must be integers

您的字符串不是 JSON 格式。

我設法通過刪除不相關的內容(不遵循 JSON 編碼)將其轉換為 JSON。

此代碼將從 JSON 字符串中獲取ID

import json
s = '''
{
   "listingReducer":{
      "selectedListing":{
         "id":2234588,
         "has_video":0,
         "refresh":1625551240,
         "category":6,
         "ketchen":1,
         "lift":1,
         "livings":1,
         "maid":null,
         "meter_price":null,
         "playground":null,
         "location":{
            "lat":26.378031,
            "lng":50.124866
         },
         "views":6075
      }
   }
}
'''

d = json.loads(s)
print(f"ID: {d['listingReducer']['selectedListing']['id']}")
Output:

ID: 2234588

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM