python:从json字符串获取特定值

2024-09-29 00:21:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从Json响应中获取精确值 如何获取特定的json值

这是我的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


Tags: 字符串importidjsonwindowrespnullprint
1条回答
网友
1楼 · 发布于 2024-09-29 00:21:55

您的字符串不是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

相关问题 更多 >