Python - JSON 使用 .ini 选项解析
Python - JSON parsing using .ini options
当地时间不错 Python 人,
我要处理一堆 JSON 回复,格式如下:
{
"responseHeader":{
"status":1,
"params":{
"indent":"true",
"fq":"recordType:Vinyl",
"wt":"json"
}
},
"response":{
"numFound":2,
"albums":[
{
"name":"Some Crappy Album",
"year":"1997",
"artist":[
"Bill's Polka Jamburri"
],
"producer":[
"Dope records"
],
},
{
"name":"Best of Foreigner",
"year":"2008",
"artist":[
"Foreginer"
],
"producer":[
"Rhino Entertainment"
],
},
]
}
}
还有一个 .ini 文件,其中包括:
[Filters]
Exclude:somekey=somevalue
Include:somekey=somevalue
我已经有了使用 urllib、urllib2、argparse 和配置解析器的代码,这些解析器能够读取大量这些记录并对数据进行处理。 我的问题是,使用我的 .ini 文件实现过滤的最佳方式是什么,我可以在其中根据字段 (Include:artist=devo) 显式检索专辑或根据字段 (Exclude:year) 排除专辑=1979)?
下面是我的 getOptionsFromConfigFile、loadJSON 和 getAlbums 函数:
def getOptionsFromConfigFile( ):
print "==========================================================================="
print "Reading in config (.ini) file params ... "
config = ConfigParser.ConfigParser()
config.read("config.ini")
ExcludeParams = config.get("Filters", "Exclude")
logging.debug(' Exclude params pulled from ini file: ' + JSONPath)
IncludeParams = config.get("Filters", "Include")
logging.debug(' Include params pulled from ini file: ' + JSONPath)
return ExcludeParams, IncludeParams;
def loadJSON( ):
print "Fetch Albums! ---> " + JSONPath
print "==========================================================================="
logging.debug('Loading ' + JSONPath)
response = urllib2.urlopen(JSONPath)
data = response.read()
values = simplejson.loads(data)
logging.debug('Dictionary pulled from ' + JSONPath)
return values;
def getAlbums( values, outputPath):
logging.debug('Getting Albums ...')
for Album in values['response']['albums']:
albumName = album['name']
storeAlbum(outputPath)
print "==========================================================================="
return;
假设您可以将 Exclude:year=1979
加载到一个字符串,您将需要获取一个元组,例如
('year', 1979)
然后,在迭代专辑的同时,您还需要迭代一些排除或包含元组的列表
# TODO: parse the exclusions and pass to this function
def getAlbums( values, output_path, inclusions=None, exclusions=None):
logging.debug('Getting Albums ...')
albums = []
for album in values['response']['albums']:
for ex_key, ex_value in exclusions:
# filter out the exclusions
if ex_key in album and album[ex_key] != ex_value:
album_name = album['name']
albums.append(album_name)
for album in albums:
store_album(album, output_path)
不过,这种方法并不完美,因为如果排除和包含重叠值会怎样?您是要添加未排除的所有内容还是仅添加包含的值?
您最好获取列表中的所有值,然后再过滤
最后,我在 ini 文件中对每个 JSON 元素、"name"、"year"、"artist"、"producer" 使用了 AND 过滤器,以及为每个过滤器创建方法。空白参数会被忽略。与我的 9 层嵌套 include/exclude 元组实现相比,这最终在代码中明显更清晰。
当地时间不错 Python 人,
我要处理一堆 JSON 回复,格式如下:
{
"responseHeader":{
"status":1,
"params":{
"indent":"true",
"fq":"recordType:Vinyl",
"wt":"json"
}
},
"response":{
"numFound":2,
"albums":[
{
"name":"Some Crappy Album",
"year":"1997",
"artist":[
"Bill's Polka Jamburri"
],
"producer":[
"Dope records"
],
},
{
"name":"Best of Foreigner",
"year":"2008",
"artist":[
"Foreginer"
],
"producer":[
"Rhino Entertainment"
],
},
]
}
}
还有一个 .ini 文件,其中包括:
[Filters]
Exclude:somekey=somevalue
Include:somekey=somevalue
我已经有了使用 urllib、urllib2、argparse 和配置解析器的代码,这些解析器能够读取大量这些记录并对数据进行处理。 我的问题是,使用我的 .ini 文件实现过滤的最佳方式是什么,我可以在其中根据字段 (Include:artist=devo) 显式检索专辑或根据字段 (Exclude:year) 排除专辑=1979)?
下面是我的 getOptionsFromConfigFile、loadJSON 和 getAlbums 函数:
def getOptionsFromConfigFile( ):
print "==========================================================================="
print "Reading in config (.ini) file params ... "
config = ConfigParser.ConfigParser()
config.read("config.ini")
ExcludeParams = config.get("Filters", "Exclude")
logging.debug(' Exclude params pulled from ini file: ' + JSONPath)
IncludeParams = config.get("Filters", "Include")
logging.debug(' Include params pulled from ini file: ' + JSONPath)
return ExcludeParams, IncludeParams;
def loadJSON( ):
print "Fetch Albums! ---> " + JSONPath
print "==========================================================================="
logging.debug('Loading ' + JSONPath)
response = urllib2.urlopen(JSONPath)
data = response.read()
values = simplejson.loads(data)
logging.debug('Dictionary pulled from ' + JSONPath)
return values;
def getAlbums( values, outputPath):
logging.debug('Getting Albums ...')
for Album in values['response']['albums']:
albumName = album['name']
storeAlbum(outputPath)
print "==========================================================================="
return;
假设您可以将 Exclude:year=1979
加载到一个字符串,您将需要获取一个元组,例如
('year', 1979)
然后,在迭代专辑的同时,您还需要迭代一些排除或包含元组的列表
# TODO: parse the exclusions and pass to this function
def getAlbums( values, output_path, inclusions=None, exclusions=None):
logging.debug('Getting Albums ...')
albums = []
for album in values['response']['albums']:
for ex_key, ex_value in exclusions:
# filter out the exclusions
if ex_key in album and album[ex_key] != ex_value:
album_name = album['name']
albums.append(album_name)
for album in albums:
store_album(album, output_path)
不过,这种方法并不完美,因为如果排除和包含重叠值会怎样?您是要添加未排除的所有内容还是仅添加包含的值?
您最好获取列表中的所有值,然后再过滤
最后,我在 ini 文件中对每个 JSON 元素、"name"、"year"、"artist"、"producer" 使用了 AND 过滤器,以及为每个过滤器创建方法。空白参数会被忽略。与我的 9 层嵌套 include/exclude 元组实现相比,这最终在代码中明显更清晰。