【问题标题】:Python and JSON(very long file)Python 和 JSON(非常长的文件)
【发布时间】:2018-02-18 16:26:58
【问题描述】:

我在论坛上搜索过,我看到了很多关于它的讨论,但没有什么比这更具体。 所以我有一个很长的 json 文件,我想将它作为字典加载到 python 中,not list。 你可以在这里查看文件https://www.bicing.cat/availability_map/getJsonObject

这是我加载文件的代码,但每次运行时,我都会收到错误: TypeError: 列表索引必须是整数,而不是 str

import json
import requests

if __name__=='__main__':
    response = requests.get("https://www.bicing.cat/availability_map  /getJsonObject")
    data=response.json()


    print data["typeStation"][22]

【问题讨论】:

  • TypeError: list indices must be integers, not str: 好吧,你的datalist"typeStation"str。这能告诉你什么吗?
  • 是的,我知道datalist.... 我怎样才能在dict 中转换data 以在json 文件中执行搜索?
  • 请在您的问题中添加示例预期输出。我真的不明白你想如何从列表中制作字典。
  • 你确定不需要这样的东西吗:print([item for item in data if item['id'] == '22'])
  • 我想要一个功能,允许通过可用的“插槽”订购自行车站并显示前 N 个站。用户还可以选择将结果按升序或降序排列(默认为降序)。参数为: -N:要显示的站数。它是可选的,默认情况下 N=10。 -order:它是可选的,默认值为降序为此我尝试将json文件读取为字典,但函数json.loadjson.loads返回列表。

标签: python json pandas cherrypy


【解决方案1】:

使用 pandas 库处理类表数据:

import pandas as pd

# Read to dataframe
df = pd.read_json("https://www.bicing.cat/availability_map/getJsonObject")

def return_stations(df, n=10, ascending=False):
    """a function allowing to order the bike-stations by available “slots” 
       and display first N stations. The user can also choose to have the 
       results in ascending or descending order (by default descending). The 
       parameters are: -N: number of stations to display. It is optional and 
       by default N=10. -order: It is optional and the default value is 
       descending"""
    return (df.sort_values(by='slots',ascending=ascending)
            .head(n).set_index('id').to_dict('i'))

# Let's print the first 3 in descending order
print(return_stations(df, n=3, ascending=False))

返回以下内容:

{10: {'address': 'Carrer Comerç',
  'addressNumber': '27',
  'bikes': 0,
  'district': 1,
  'lat': 41.38498,
  'lon': 2.18417,
  'name': '10 - C/ COMERÇ, 27',
  'nearbyStations': '9,14,115,389',
  'slots': 33,
  'stationType': 'BIKE',
  'status': 'CLS',
  'zip': 8003},
 213: {'address': 'Sant Fe de Nou Mèxic',
  'addressNumber': '2',
  'bikes': 0,
  'district': 6,
  'lat': 41.393783,
  'lon': 2.135078,
  'name': '213 - C/ SANTA FE DE NOU MÈXIC, 2',
  'nearbyStations': '207,208,214,215',
  'slots': 33,
  'stationType': 'BIKE',
  'status': 'OPN',
  'zip': 8017},
 326: {'address': 'Balmes',
  'addressNumber': '409',
  'bikes': 0,
  'district': 6,
  'lat': 41.407384,
  'lon': 2.1383,
  'name': '326 - C/BALMES, 409',
  'nearbyStations': '321,327,328,330',
  'slots': 33,
  'stationType': 'BIKE',
  'status': 'OPN',
  'zip': 8022}}

哦,还有一件事......看到你在那里得到了 lat lng: 我们可以编写一个 geojson 文件并将其绘制在地图上,将文件放到 geojson.io 上。这是一个函数:

def return_geojson(df, latlng):
    d = dict(type="FeatureCollection",features=[])

    for ind,row in df.fillna('').iterrows():
        p = row.drop(latlng).to_dict()
        g = dict(type="Point",coordinates=list(row[latlng])[::-1])
        f = dict(type="Feature", properties=p, geometry=g)
        d['features'].append(f)

    return d

with open('map.geojson','w') as f:
    d = return_geojson(df,['lat','lon'])
    json.dump(d,f)

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多