如何从键中抓取 JSON 值?

How can I scrape JSON value from key?

import requests
from datetime import datetime

gg = []

now = datetime.now()
current_time = now.strftime("%Y-%m-%dT%H:%M:%S")

url = ("https://sportsbook-sm-distribution-api.nsoft.com/api/v1/events?deliveryPlatformId=3&dataFormat=%7B%22default%22:%22object%22,%22events%22:%22array%22,%22outcomes%22:%22object%22%7D&language=%7B%22default%22:%22sr-Latn%22,%22events%22:%22sr-Latn%22,%22sport%22:%22sr-Latn%22,%22category%22:%22sr-Latn%22,%22tournament%22:%22sr-Latn%22,%22team%22:%22sr-Latn%22,%22market%22:%22sr-Latn%22%7D&timezone=Europe%2FBelgrade&company=%7B%7D&companyUuid=4dd61a16-9691-4277-9027-8cd05a647844&filter[sportId]=3&filter[from]={}&sort=categoryPosition,categoryName,tournamentPosition,tournamentName,startsAt&offerTemplate=WEB_OVERVIEW&shortProps=1").format(current_time)

response = requests.get(url)
matches = response.json()
print(matches) #This is my json document

我正在尝试从博彩网站上获取赔率。我是 python 的新手,需要一些帮助。

键“b”中存储了某种“奇怪的 ID”。所以基本上对于这个 json 文件中的每个匹配项,如果匹配项包含值为 2763 的键“b”,我想抓取键“g”的值并将其存储在我的列表“gg”中(在键“g”中我想刮掉的值很奇怪)。但是,如果匹配项不包含值为 2763 的键“b”,对于该匹配项,我只想附加一次“1.00”以列出“gg”。

for match in matches:
    mat = matches['data']['events']
    for s in range(len(mat)):
        o = mat[s]['o']
        for element in o:
            h = o[element]['h']
            for x in h:
                if h[x]['b'] == 2763:
                gg.append(h[x]['g'])

使用此命令我可以排除赔率,但如果匹配项没有 'b':2763 (oddid)

,我不知道如何将“1.00”附加到 GG

据我所知,你的问题。这应该是解决方案。

   json = {
        'b': 2763,
        'g': 'odd number'
    }
    
    x = 'b'
    y = 2763
    gg = []
    
    for key, value in json.items():
        if x == key and y == value:  # if finds b: 2763
            gg.append(json.get('g'))
        elif x == key and y != value:
            gg.append(1.00)
            break

您可以使用理解来减少行数。

我没有验证您的代码,但我假设它可以工作并且您了解它的作用。你需要的是一面旗帜。标志只是一个布尔值 (True/False),我们将其命名为 has_2763。你只需要在每场比赛开始时重置它

for match in matches:
    mat = matches['data']['events']
    for s in range(len(mat)):
        has_2763 = False
        o = mat[s]['o']
        for element in o:
            h = o[element]['h']
            for x in h:
                if h[x]['b'] == 2763:
                    gg.append(h[x]['g'])
                    has_2763 = True
        if not has_2763:
            gg.append("1.00")