DeepSearch只返回索引号

2024-06-01 23:49:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用DeepSearch来查找一个项目,这很有效。我只想返回['members']的索引ID。在这种情况下,ID是[1]。有什么办法吗

任何帮助都将不胜感激,我仍在学习Python,因此正在努力解决这些问题

代码:

from deepdiff import grep
obj = response.json()
item = ".rep"
ds = obj | grep(item, verbose_level=2)
print(ds)

返回:

matched_values': {"root['data'][1]['members'][0]['address']"}}

是否可以使用正则表达式对其进行过滤\D将过滤为1和0。如何删除0而只保留1


Tags: 项目代码fromimportidobjresponseds
1条回答
网友
1楼 · 发布于 2024-06-01 23:49:48

我用以下代码解决了这个问题:

import requests
from deepdiff import grep
import re

response = s.get(url)
obj = response.json()
item = ".rep"
ds = obj | grep(item)
print(ds) # {'matched_values': {"root['data'][8]['members'][0]['address']"}}
aa = re.search(r"\d", str(ds))
print(aa) # <re.Match object; span=(34, 35), match='8'>
if aa is not None:
    bb = re.findall(r'(\d)', str(ds))
    print(bb) # ['8', '0']
    if len(bb) == 3: # The list may be three characters total
        bb.pop(2) # The third character is not needed
        print(bb)
        bb = ''.join(str(i) for i in bb[:2]) # convert the list to a string
        print(bb)
    else:
        bb = re.search(r'(\d)', str(ds)) # find only the first int as that's all that's needed
        print(format(bb.group(0))) # 8
else:
    print('no matches found')

相关问题 更多 >