首页 > 解决方案 > 来自 API 的 Open.json 文件

问题描述

谁能提供打开此文件内容的代码?

url = ' https://datos.madrid.es/egob/catalogo/202625-0-aparcamientos-publicos.json '

我已经尝试过requests.get(url).json()并且我只是不断收到以下错误,不管我做什么:

JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

标签: jsonapipython-requests

解决方案


服务器需要一个 User-Agent 标头。尝试:

import requests

url = 'https://datos.madrid.es/egob/catalogo/202625-0-aparcamientos-publicos.json'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
response = requests.get(url, headers=headers)
print(response.json())

输出:

{'@context': {'c': 'http://www.w3.org/2002/12/cal#', 'dcterms': 'http://purl.org/dc/terms/', 'geo': 'http://www.w3.org/2003/01/geo/wgs84_pos#', 'loc': 'http://purl.org/ctic/infraestructuras/localizacion#', 'org': 'http://purl.org/ctic/infraestructuras/organizacion#', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'schema': 'https://schema.org/', 'title': 'vcard:fn', 'id': 'dcterms:identifier', 'relation': 'dcterms:relation', 'references': 'dcterms:references', 'address': 'vcard:adr', 'area': 'loc:barrio', 'district': 'loc :distrito', ...

要获取 @graph 对象,只需使用普通的 JSON 解析:

print(response.json()['@graph'])

或者,如果您希望将其作为字符串:

import json
...
print(json.dumps(response.json()['@graph']))

或遍历图形对象:

for graph in response.json()['@graph']:
    print(json.dumps(graph))

推荐阅读