Python:从文件夹中读取多个json文件 [英] Python: Read several json files from a folder
问题描述
我想知道如何从单个文件夹中读取几个json
文件(无需指定文件名,只是它们是json文件).
I would like to know how to read several json
files from a single folder (without specifying the files names, just that they are json files).
还可以将它们转换为pandas
DataFrame吗?
Also, it is possible to turn them into a pandas
DataFrame?
能给我一个基本的例子吗?
Can you give me a basic example?
推荐答案
One option is listing all files in a directory with os.listdir and then finding only those that end in '.json':
import os, json
import pandas as pd
path_to_json = 'somedir/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
print(json_files) # for me this prints ['foo.json']
现在您可以使用熊猫 DataFrame.from_dict 读取json(此时为python字典)到熊猫数据框:
Now you can use pandas DataFrame.from_dict to read in the json (a python dictionary at this point) to a pandas dataframe:
montreal_json = pd.DataFrame.from_dict(many_jsons[0])
print montreal_json['features'][0]['geometry']
打印:
{u'type': u'Point', u'coordinates': [-73.6051013, 45.5115944]}
在这种情况下,我将一些json附加到列表many_jsons
中.我列表中的第一个json实际上是 geojson ,其中包含蒙特利尔的一些地理数据.我已经很熟悉内容了,所以我打印出了几何图形",它给了我蒙特利尔的魅力.
In this case I had appended some jsons to a list many_jsons
. The first json in my list is actually a geojson with some geo data on Montreal. I'm familiar with the content already so I print out the 'geometry' which gives me the lon/lat of Montreal.
以下代码总结了以上所有内容:
The following code sums up everything above:
import os, json
import pandas as pd
# this finds our json files
path_to_json = 'json/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
# here I define my pandas Dataframe with the columns I want to get from the json
jsons_data = pd.DataFrame(columns=['country', 'city', 'long/lat'])
# we need both the json and an index number so use enumerate()
for index, js in enumerate(json_files):
with open(os.path.join(path_to_json, js)) as json_file:
json_text = json.load(json_file)
# here you need to know the layout of your json and each json has to have
# the same structure (obviously not the structure I have here)
country = json_text['features'][0]['properties']['country']
city = json_text['features'][0]['properties']['name']
lonlat = json_text['features'][0]['geometry']['coordinates']
# here I push a list of data into a pandas DataFrame at row given by 'index'
jsons_data.loc[index] = [country, city, lonlat]
# now that we have the pertinent json data in our DataFrame let's look at it
print(jsons_data)
这对我来说是打印的:
country city long/lat
0 Canada Montreal city [-73.6051013, 45.5115944]
1 Canada Toronto [-79.3849008, 43.6529206]
了解此代码对于在目录名"json"中有两个geojsons可能会有所帮助.每个json具有以下结构:
It may be helpful to know that for this code I had two geojsons in a directory name 'json'. Each json had the following structure:
{"features":
[{"properties":
{"osm_key":"boundary","extent":
[-73.9729016,45.7047897,-73.4734865,45.4100756],
"name":"Montreal city","state":"Quebec","osm_id":1634158,
"osm_type":"R","osm_value":"administrative","country":"Canada"},
"type":"Feature","geometry":
{"type":"Point","coordinates":
[-73.6051013,45.5115944]}}],
"type":"FeatureCollection"}
这篇关于Python:从文件夹中读取多个json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!