当前位置: 首页 > 知识库问答 >
问题:

在进行API调用后,如何从JSON dice访问dice?[重复]

伏砚
2023-03-14

我想访问字典中的值,但我无法做响应[“建立”],因为当它被返回时,字典中有一个奇怪的b符号。如何摆脱b符号,以便我可以访问字典?

b'{"establishments":[{"FHRSID":775937,"ChangesByServerID":0,"LocalAuthorityBusinessID":"13/00068/COMM","BusinessName":"Lexington Catering - Fidessa Restaurant","BusinessType":"Restaurant/Cafe/Canteen","BusinessTypeID":1,"AddressLine1":"Block E First To Seventh Floors Dukes Court Duke Street Woking Surrey","AddressLine2":"","AddressLine3":"","AddressLine4":"","PostCode":"GU21 5BH","Phone":"","RatingValue":"5","RatingKey":"fhrs_5_cy-gb","RatingDate":"2020-01-10T00:00:00","LocalAuthorityCode":"315","LocalAuthorityName":"Woking","LocalAuthorityWebSite":"http://www.woking.gov.uk","LocalAuthorityEmailAddress":"emma.bourne@woking.gov.uk","scores":{"Hygiene":0,"Structural":0,"ConfidenceInManagement":0},"SchemeType":"FHRS","geocode":{"longitude":"-0.554158","latitude":"51.320771"},"RightToReply":"","Distance":null,"NewRatingPending":false,"meta":{"dataSource":null,"extractDate":"0001-01-01T00:00:00","itemCount":0,"returncode":null,"totalCount":0,"totalPages":0,"pageSize":0,"pageNumber":0},"links":[{"rel":"self","href":"https://api.ratings.food.gov.uk/establishments/775937"}]},{"FHRSID":1474143,"ChangesByServerID":0,"LocalAuthorityBusinessID":"22/00013/COMM","BusinessName":"Duke\'s Bar & Deli","BusinessType":"Other catering premises","BusinessTypeID":7841,"AddressLine1":"Dukes Bar And Deli 3 Duke Street Woking Surrey","AddressLine2":"","AddressLine3":"","AddressLine4":"","PostCode":"GU21 5BH","Phone":"","RatingValue":"4","RatingKey":"fhrs_4_cy-gb","RatingDate":"2022-02-24T00:00:00","LocalAuthorityCode":"315","LocalAuthorityName":"Woking","LocalAuthorityWebSite":"http://www.woking.gov.uk","LocalAuthorityEmailAddress":"emma.bourne@woking.gov.uk","scores":{"Hygiene":10,"Structural":0,"ConfidenceInManagement":10},"SchemeType":"FHRS","geocode":{"longitude":null,"latitude":null},"RightToReply":"","Distance":null,"NewRatingPending":false,"meta":{"dataSource":null,"extractDate":"0001-01-01T00:00:00","itemCount":0,"returncode":null,"totalCount":0,"totalPages":0,"pageSize":0,"pageNumber":0},"links":[{"rel":"self","href":"https://api.ratings.food.gov.uk/establishments/1474143"}]}],"meta":{"dataSource":"Lucene","extractDate":"2022-09-03T00:50:19.6362148+01:00","itemCount":2,"returncode":"OK","totalCount":2,"totalPages":1,"pageSize":5000,"pageNumber":1},"links":[{"rel":"self","href":"https://api.ratings.food.gov.uk/establishments?address=gu21%205bh"}]}'

这是我的代码

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
    "Upgrade-Insecure-Requests": "1",
    "DNT": "1",
    # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "cy-GB",
    "Accept-Encoding": "gzip, deflate, br",
    "x-api-version": "2",
    # 'Content-Type': 'application/json'
}

def get_web_page_content(post_code):
    print('post_code', post_code)
    BOMS = [
        codecs.BOM,
        codecs.BOM_BE,
        codecs.BOM_LE,
        codecs.BOM_UTF8,
        codecs.BOM_UTF16,
        codecs.BOM_UTF16_BE,
        codecs.BOM_UTF16_LE,
        codecs.BOM_UTF32,
        codecs.BOM_UTF32_BE,
        codecs.BOM_UTF32_LE,
    ]

    url = rf'https://api.ratings.food.gov.uk/Establishments?address={post_code}'
    time.sleep(5)
    response = requests.get(url, headers=headers)
    data = response.content

    for BOM in BOMS:
        if data.startswith(BOM):
            data = json.loads(data[len(BOM):])
            break
    return data


if __name__ == '__main__':
    response = get_web_page_content('GU21 5BH')
    print('response', response)

共有3个答案

储毅
2023-03-14

您可以使用response.json获取JSON:

print("response", response.json)

奇怪的b表示它是一个字节对象。

江亮
2023-03-14

“奇怪的”b'...'符号意味着你有字节对象 - 这就是响应.content返回的内容。要解码 json string,请使用 response.json()

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
    "Upgrade-Insecure-Requests": "1",
    "DNT": "1",
    "Accept-Language": "cy-GB",
    "Accept-Encoding": "gzip, deflate, br",
    "x-api-version": "2",
}


def get_web_page_content(post_code):
    print("post_code", post_code)

    url = rf"https://api.ratings.food.gov.uk/Establishments?address={post_code}"
    response = requests.get(url, headers=headers)
    return response.json()  # <-- use .json() here to parse JSON response


if __name__ == "__main__":
    response = get_web_page_content("GU21 5BH")
    print("response", response)

版画:

post_code GU21 5BH
response {'establishments': [{'FHRSID': 775937, 'ChangesByServerID': 0, 'LocalAuthorityBusinessID': '13/00068/COMM', 'BusinessName': 'Lexington Catering - Fidessa Restaurant', 'BusinessType': 'Restaurant/Cafe/Canteen', 'BusinessTypeID': 1, 'AddressLine1': 'Block E First To Seventh Floors Dukes Court Duke Street Woking Surrey', 'AddressLine2': '', 'AddressLine3': '', 'AddressLine4': '', 'PostCode': 'GU21 5BH', 'Phone': '', 'RatingValue': '5', 'RatingKey': 'fhrs_5_cy-gb', 'RatingDate': '2020-01-10T00:00:00', 'LocalAuthorityCode': '315', 'LocalAuthorityName': 'Woking', 'LocalAuthorityWebSite': 'http://www.woking.gov.uk', 'LocalAuthorityEmailAddress': 'emma.bourne@woking.gov.uk', 'scores': {'Hygiene': 0, 'Structural': 0, 'ConfidenceInManagement': 0}, 'SchemeType': 'FHRS', 'geocode': {'longitude': '-0.554158', 'latitude': '51.320771'}, 'RightToReply': '', 'Distance': None, 'NewRatingPending': False, 'meta': {'dataSource': None, 'extractDate': '0001-01-01T00:00:00', 'itemCount': 0, 'returncode': None, 'totalCount': 0, 'totalPages': 0, 'pageSize': 0, 'pageNumber': 0}, 'links': [{'rel': 'self', 'href': 'https://api.ratings.food.gov.uk/establishments/775937'}]}, {'FHRSID': 1474143, 'ChangesByServerID': 0, 'LocalAuthorityBusinessID': '22/00013/COMM', 'BusinessName': "Duke's Bar & Deli", 'BusinessType': 'Other catering premises', 'BusinessTypeID': 7841, 'AddressLine1': 'Dukes Bar And Deli 3 Duke Street Woking Surrey', 'AddressLine2': '', 'AddressLine3': '', 'AddressLine4': '', 'PostCode': 'GU21 5BH', 'Phone': '', 'RatingValue': '4', 'RatingKey': 'fhrs_4_cy-gb', 'RatingDate': '2022-02-24T00:00:00', 'LocalAuthorityCode': '315', 'LocalAuthorityName': 'Woking', 'LocalAuthorityWebSite': 'http://www.woking.gov.uk', 'LocalAuthorityEmailAddress': 'emma.bourne@woking.gov.uk', 'scores': {'Hygiene': 10, 'Structural': 0, 'ConfidenceInManagement': 10}, 'SchemeType': 'FHRS', 'geocode': {'longitude': None, 'latitude': None}, 'RightToReply': '', 'Distance': None, 'NewRatingPending': False, 'meta': {'dataSource': None, 'extractDate': '0001-01-01T00:00:00', 'itemCount': 0, 'returncode': None, 'totalCount': 0, 'totalPages': 0, 'pageSize': 0, 'pageNumber': 0}, 'links': [{'rel': 'self', 'href': 'https://api.ratings.food.gov.uk/establishments/1474143'}]}], 'meta': {'dataSource': 'Lucene', 'extractDate': '2022-09-03T00:59:03.9485729+01:00', 'itemCount': 2, 'returncode': 'OK', 'totalCount': 2, 'totalPages': 1, 'pageSize': 5000, 'pageNumber': 1}, 'links': [{'rel': 'self', 'href': 'https://api.ratings.food.gov.uk/establishments?address=gu21%205bh'}]}
谭昕
2023-03-14

您可以访问不同格式的响应,例如字节,json或原始。在你的情况下,你正在使用字节的方式,这就是为什么结果是以字节的形式,以b为前缀,如果你想像语法一样以字典的形式访问它,即响应[“建立”],那么你需要使用repont.json()

就像,

import requests
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
    "Upgrade-Insecure-Requests": "1",
    "DNT": "1",
    # "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "cy-GB",
    "Accept-Encoding": "gzip, deflate, br",
    "x-api-version": "2",
    #'Content-Type': 'application/json'
}

def get_web_page_content(post_code):
    print('post_code', post_code)

    url = rf'https://api.ratings.food.gov.uk/Establishments?address={post_code}'
    response = requests.get(url, headers=headers)
    data = response.json()
    return data

if __name__ == '__main__':
    response = get_web_page_content('GU21 5BH')
    print('response', response)
    print('establishments', response["establishments"])
 类似资料:
  • 我正在尝试使用Google API获得<code>离线访问</code>。我必须从谷歌日历中提取数据,而无需用户每次登录。 我已将以下内容添加到我的 Gem 文件中: https://accounts.google.com/o/oauth2/auth?access_type=offline 我错过什么了吗?

  • 我使用postman测试了一个API。使用postman,我设法生成了一个令牌。 从postman那里,我通过一个get请求,使用以下内容和以下详细信息获取了用户的所有数据: 在授权类型下,我选择了“无记名令牌”并将令牌粘贴在其各自的字段中。 当我单击发送时,我得到了一个用户数据的成功响应。 在PHP中,如何在PHP函数中执行相同的api调用(使用id、电子邮件和令牌)? 我试过这个: 但当我查看

  • 我有下面的AuthenticationResponse模型,用于使用Reform2的3个api调用。如果我进行verifyEmail调用f.e.,JSON响应主体只包含有效电子邮件的属性(例如{“validEmail”:true})。其他2个调用仅包含“ResetSuccessful”或其他4个调用的属性。 我如何确保/检查收到verifyEmail呼叫f.e.的响应时,它包含validEmail

  • 问题是它对我的测试广告起作用,而对生产广告不起作用。说用户需要在使用图形API之前许可应用程序。(对于生产广告,我只有用户可以添加用户特权,但不能添加应用程序特权。我猜测,要使该方案工作,我需要先许可该广告的全局管理)。最终,我将Web站点和Web API的Azure广告应用程序合并在一起,并且它使用了带有引导令牌的相同的代理方法。但我想知道如何使它与2个应用程序正常工作。

  • 问题内容: 好的,这里是twitter API, 任何人都可以给我有关如何使用Meteor调用此API或链接的任何提示吗 更新:: 这是我尝试过的代码,但未显示任何响应 问题答案: 您要定义checkTwitter Meteor.method 内部 客户范围的块。因为您不能从客户端调用跨域(除非使用jsonp),所以您必须将此块放在一个块中。 顺便说一句,每个文档,在客户端的checkTwitte

  • 我正在使用Lusita的PHP Oauth库(https://github.com/Lusitanian/PHPoAuthLib)。 在用户在我的应用程序中获得授权后,我收到了访问令牌和访问令牌密钥的值。现在有了这些值,我想对API进行身份验证调用。如何使用Access Token、Access Token Secret以及Consumer Key和Consumer Secret的值进行调用?我不