python實現(xiàn)提取str字符串/json中多級目錄下的某個值
字符串多級目錄取值:
比如說:
你response接收到的數(shù)據(jù)是這樣的。
你現(xiàn)在只需要取到itemstring 這個字段下的值。其他的都不要!
思路就是:字符串是個json格式(或轉(zhuǎn)為json格式),然后str轉(zhuǎn)為字典dict,然后循環(huán)遍歷按照key來取值。
你的data是個字典 然后item_list是data的Key ,item_list是個數(shù)組,這個里面的數(shù)組中的每個元素都是一個字典。
因此就是dict多級路徑按key取值。
# 多級目錄提取-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'])結果》》》<class ’requests.models.Response’><class ’str’><class ’dict’>提取的值。。。。。。出現(xiàn)
最后獲取出來的是:
所有itemstring字段的值:(遍歷出來的)
看得懂的就是需要的。這是我調(diào)用騰訊API,然后出現(xiàn)返回值是一個含有N個字段的json數(shù)據(jù),最后我提取出來OCR識別的部分。其他的沒有要。
補充拓展:按照Json的層級提取各個字段的實例
如下所示:
String s = '{'error':0,'status':'success','results':[{'currentCity':'青島','index':[{'title':'穿衣','zs':'較冷','tipt':'穿衣指數(shù)','des':'建議著厚外套加毛衣等服裝。年老體弱者宜著大衣、呢外套加羊毛衫。'},{'title':'紫外線強度','zs':'最弱','tipt':'紫外線強度指數(shù)','des':'屬弱紫外線輻射天氣,無需特別防護。若長期在戶外,建議涂擦SPF在8-12之間的防曬護膚品。'}],}]}'; 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)容帶有中括號[],所以要轉(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)容帶有中括號[],所以要轉(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實現(xiàn)提取str字符串/json中多級目錄下的某個值就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. 父div高度不能自適應子div高度的解決方案2. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法3. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)4. JSP狀態(tài)管理的簡單介紹5. jsp+mysql實現(xiàn)網(wǎng)頁的分頁查詢6. servlet+jsp實現(xiàn)過濾器 防止用戶未登錄訪問7. 選擇模式 - XSL教程 - 28. Java之JSP教程九大內(nèi)置對象詳解(中篇)9. 淺談XML Schema中的elementFormDefault屬性10. ASP中SELECT下拉菜單同時獲取VALUE和TEXT值的實現(xiàn)代碼
