久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

python實(shí)現(xiàn)提取str字符串/json中多級目錄下的某個值

瀏覽:2日期:2022-08-05 17:39:57

字符串多級目錄取值:

比如說:

你response接收到的數(shù)據(jù)是這樣的。

你現(xiàn)在只需要取到itemstring 這個字段下的值。其他的都不要!

python實(shí)現(xiàn)提取str字符串/json中多級目錄下的某個值

思路就是:字符串是個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'])結(jié)果》》》<class ’requests.models.Response’><class ’str’><class ’dict’>提取的值。。。。。。出現(xiàn)

最后獲取出來的是:

所有itemstring字段的值:(遍歷出來的)

python實(shí)現(xiàn)提取str字符串/json中多級目錄下的某個值

看得懂的就是需要的。這是我調(diào)用騰訊API,然后出現(xiàn)返回值是一個含有N個字段的json數(shù)據(jù),最后我提取出來OCR識別的部分。其他的沒有要。

補(bǔ)充拓展:按照J(rèn)son的層級提取各個字段的實(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中多級目錄下的某個值就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 肥西县| 贺州市| 泸州市| 富宁县| 竹山县| 张家界市| 翼城县| 四平市| 微博| 临西县| 乌兰县| 南郑县| 小金县| 永州市| 望奎县| 石台县| 大埔区| 红河县| 邢台县| 万载县| 文化| 禹城市| 泊头市| 马鞍山市| 烟台市| 延安市| 龙南县| 九寨沟县| 秀山| 永定县| 民权县| 陆川县| 林口县| 黄山市| 松溪县| 体育| 思南县| 蚌埠市| 姚安县| 福鼎市| 香格里拉县|