从json响应的特定文本后获取数字

问题描述 投票:-1回答:3

[使用Python,我试图从与关键字numHits的字段值相对应的字符串中提取数字1631。关键字是固定的。如何使用正则表达式?

{'statusCode': 200,
 'numHits': 1631,
 'hits': [{'lastSeen': '2019-09-25',
   'imageHeight': 360,
python json regex
3个回答
0
投票

这里是一个例子:

导入jsonjson_data = json.loads(response_data)打印(json_data ['numHits'])


0
投票

一个完整的例子是:

import requests

response = requests.get('your_url')
your_data = response.json()
print(your_data['numHits'])

0
投票
import re

json_str = "{'statusCode': 200, 'numHits': 1631, 'hits': [{'lastSeen': '2019-09-25', 'imageHeight': 360,..."

r = re.compile(r"'numHits':\s+(\d+)")

res = r.search(json_str) # <_sre.SRE_Match object; span=(20, 35), match="'numHits': 1631">
res.group(1) # '1631'


# be careful with non maching strings
res = r.search("asd") # None
res.group(1) # -> AttributeError: 'NoneType' object has no attribute 'group'

© www.soinside.com 2019 - 2024. All rights reserved.