我有一个根据JSON创建的字典。我想通过包含它们的键的数组来访问字典中的项目。可视化JSON:
{
"name": "Chiel",
"industry": {
"IndustryName": "Computer Science",
"company": {
"companyName": "Apple",
"address": {
"streetName": "Apple Park Way",
"streetNumber": "1"
}
}
},
"hobby": {
"hobbyName": "Music production",
"genre": {
"genreName": "Deep house",
"genreYearOrigin": "1980"
}
}
}
请参见以下代码示例:
#create dict
jsonData = '{"name":"Chiel","industry":{"IndustryName":"Computer Science","company":{"companyName":"Apple","address":{"streetName":"Apple Park Way","streetNumber":"1"}}},"hobby":{"hobbyName":"Music production","genre":{"genreName":"Deep house","genreYearOrigin":"1980"}}}'
dictionary = json.loads(jsonData)
#Referencing dict for 'streetName', from array, hardcoded.
companyElements = ["industry", "company", "address", "streetName"]
print(dictionary[companyElements[0]][companyElements[1]][companyElements[2]][companyElements[3]])
#Referencing dict for 'genreName', from array, hardcoded.
hobbyElements = ["hobby", "genre", "genreName"]
print(dictionary[hobbyElements[0]][hobbyElements[1]][hobbyElements[2]])
问题在于,对字典的访问已完成硬编码。换句话说,有使用的数字(0、1、2、3)。
是否可以通过数组访问字典,但进行软编码?那么在不使用数字的情况下将数组(或其他数据结构)传递给字典吗?如果是这样,一个人怎么能做到这一点?
答案 0 :(得分:1)
(从您提供的示例中)可能的解决方案是:
def get_element(dictionary, array):
x = dictionary.copy()
for i in array:
x = x[i]
return x
companyElements = ["industry", "company", "address", "streetName"]
hobbyElements = ["hobby", "genre", "genreName"]
print(get_element(dictionary, companyElements))
print(get_element(dictionary, hobbyElements))
答案 1 :(得分:1)
您可以编写一个迭代给定键的函数。
请注意,如果JSON中缺少一个或多个键,则以下实现将不会捕获异常:
import json
import copy
#create dict
jsonData = '{"name":"Chiel","industry":{"IndustryName":"Computer Science","company":{"companyName":"Apple","address":{"streetName":"Apple Park Way","streetNumber":"1"}}},"hobby":{"hobbyName":"Music production","genre":{"genreName":"Deep house","genreYearOrigin":"1980"}}}'
dictionary = json.loads(jsonData)
#Referencing dict for 'streetName', from array, hardcoded.
companyElements = ["industry", "company", "address", "streetName"]
#Referencing dict for 'genreName', from array, hardcoded.
hobbyElements = ["hobby", "genre", "genreName"]
def get_dict_value(data, keys):
result = copy.deepcopy(data)
for key in keys:
result = result[key]
return result
print( get_dict_value(dictionary, companyElements) )
print( get_dict_value(dictionary, hobbyElements) )
结果:
Apple Park Way
Deep house
答案 2 :(得分:1)
您可以使用pandas库。因为它是用C编写的,所以它在Python中非常有效地处理文件操作。 您可以在Pandas中使用json_normalize函数来完成此任务。
参考-https://www.kaggle.com/jboysen/quick-tutorial-flatten-nested-json-in-pandas
import json
file=open('kk.json')
inp=json.load(file)
print(json_normalize(inp))