繁体   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