我有一个API,其响应是json,如下所示:
page = requests.get('http://finance.sina.com.cn/chanjing/cyxw/2015-12-17/doc-ifxmttcn4893506.shtml')
print page.text
soup = BeautifulSoup(page.text)
soup.prettify()
print soup
如何编写一个python程序,它将为我提供密钥{
"a":1,
"b":2,
"c":[
{
"d":4,
"e":5,
"f":{
"g":6
}
}
]
}
。我试过的是:
['d','e','g']
答案 0 :(得分:1)
仅返回不包含字典作为其值的键的函数。
jsonData = {
"a": 1,
"b": 2,
"c": [{
"d": 4,
"e": 5,
"f": {
"g": 6
}
}]
}
def get_simple_keys(data):
result = []
for key in data.keys():
if type(data[key]) != dict:
result.append(key)
else:
result += get_simple_keys(data[key])
return result
print get_simple_keys(jsonData['c'][0])
避免使用递归更改行result += get_simple_keys(data[key])
到result += data[key].keys()
答案 1 :(得分:0)
试试这个,
dct = {
"a":1,
"b":2,
"c":[
{
"d":4,
"e":5,
"f":{
"g":6
}
}
]
}
k=dct["c"][0]
for key in k.keys():
print key