python實(shí)現(xiàn)提取str字符串/json中多級目錄下的某個(gè)值
字符串多級目錄取值:
比如說:
你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多級路徑按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'])結(jié)果》》》<class ’requests.models.Response’><class ’str’><class ’dict’>提取的值。。。。。。出現(xiàn)
最后獲取出來的是:
所有itemstring字段的值:(遍歷出來的)
看得懂的就是需要的。這是我調(diào)用騰訊API,然后出現(xiàn)返回值是一個(gè)含有N個(gè)字段的json數(shù)據(jù),最后我提取出來OCR識別的部分。其他的沒有要。
補(bǔ)充拓展:按照J(rèn)son的層級提取各個(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)容帶有中括號[],所以要轉(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實(shí)現(xiàn)提取str字符串/json中多級目錄下的某個(gè)值就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯問題分析2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. ASP的Global.asa文件技巧用法5. php測試程序運(yùn)行速度和頁面執(zhí)行速度的代碼6. html清除浮動的6種方法示例7. SharePoint Server 2019新特性介紹8. ASP中if語句、select 、while循環(huán)的使用方法9. React+umi+typeScript創(chuàng)建項(xiàng)目的過程10. Vue+elementUI下拉框自定義顏色選擇器方式
