简体   繁体   中英

python : get specific value from json string

I Need to Exact Value from Json response how can I get a specific json value python ???

this is my Json string I need to extract Id value

"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

}
}

this my python code :

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'])

.
.
.

And this is the Error

TypeError: string indices must be integers

Your string is not in JSON format.

I have managed to convert it into JSON by removing irrelevant content (that doesn't follow JSON encoding).

This code will get you the ID from the JSON string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM