python實(shí)現(xiàn)提取str字符串/json中多級(jí)目錄下的某個(gè)值
字符串多級(jí)目錄取值:
比如說:
你response接收到的數(shù)據(jù)是這樣的。
你現(xiàn)在只需要取到itemstring 這個(gè)字段下的值。其他的都不要!
思路就是:字符串是個(gè)json格式(或轉(zhuǎn)為json格式),然后str轉(zhuǎn)為字典dict,然后循環(huán)遍歷按照key來取值。
你的data是個(gè)字典 然后item_list是data的Key ,item_list是個(gè)數(shù)組,這個(gè)里面的數(shù)組中的每個(gè)元素都是一個(gè)字典。
因此就是dict多級(jí)路徑按key取值。
# 多級(jí)目錄提取-dictprint(type(response))print(type(response.text))result = json.loads(resp.text) # 字符串轉(zhuǎn)字典print(type(result))for i in result['data']['item_list']: print(i['itemstring'])結(jié)果》》》<class ’requests.models.Response’><class ’str’><class ’dict’>提取的值。。。。。。出現(xiàn)
最后獲取出來的是:
所有itemstring字段的值:(遍歷出來的)
看得懂的就是需要的。這是我調(diào)用騰訊API,然后出現(xiàn)返回值是一個(gè)含有N個(gè)字段的json數(shù)據(jù),最后我提取出來OCR識(shí)別的部分。其他的沒有要。
補(bǔ)充拓展:按照J(rèn)son的層級(jí)提取各個(gè)字段的實(shí)例
如下所示:
String s = '{'error':0,'status':'success','results':[{'currentCity':'青島','index':[{'title':'穿衣','zs':'較冷','tipt':'穿衣指數(shù)','des':'建議著厚外套加毛衣等服裝。年老體弱者宜著大衣、呢外套加羊毛衫。'},{'title':'紫外線強(qiáng)度','zs':'最弱','tipt':'紫外線強(qiáng)度指數(shù)','des':'屬弱紫外線輻射天氣,無需特別防護(hù)。若長期在戶外,建議涂擦SPF在8-12之間的防曬護(hù)膚品。'}],}]}'; JSONObject jsonObject = JSON.parseObject(s); //提取出error為 0 int error = (int) jsonObject.get('error'); System.out.println('error:' + error); //提取出status為 success String status = jsonObject.getString('status'); System.out.println('status:' + status); //注意:results中的內(nèi)容帶有中括號(hào)[],所以要轉(zhuǎn)化為JSONArray類型的對象 JSONArray result = jsonObject.getJSONArray('results'); for (int i = 0; i < result.size(); i++) { //提取出currentCity為 青島 String currentCity = result.getJSONObject(i).getString('currentCity'); System.out.println('currentCity:' + currentCity); //注意:index中的內(nèi)容帶有中括號(hào)[],所以要轉(zhuǎn)化為JSONArray類型的對象 JSONArray index = result.getJSONObject(i).getJSONArray('index'); for (int j = 0; j < index.size(); j++) { String title = index.getJSONObject(j).getString('title'); System.out.println('title:' + title); String zs = index.getJSONObject(j).getString('zs'); System.out.println('zs:' + zs); String tipt = index.getJSONObject(j).getString('tipt'); System.out.println('tipt:' + tipt); String des = index.getJSONObject(j).getString('des'); System.out.println('des:' + des); } } }
以上這篇python實(shí)現(xiàn)提取str字符串/json中多級(jí)目錄下的某個(gè)值就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息2. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法3. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明4. jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. asp中response.write("中文")或者js中文亂碼問題8. PHP設(shè)計(jì)模式中工廠模式深入詳解9. CSS hack用法案例詳解10. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測可用)
