我希望能够使用单个“ nested_key”变量从一组(任意深度)的嵌套字典中获取一个值。
如果我有字典,可以像这样简单地将其编入索引:
create procedure readDataFromJSON @data nvarchar(4000)
as
begin
select
contributor,difficulty,rating,instructions,[name],preptime,cooktime,imgurl,protien,fats,carbs,fiber,reciepdescription
into #tmprecipe
from OPENJSON(@data,'$.Rootobject.recipe')
WITH (
RecipeContributor varchar(100) '$.RecipeContributor' as contributor,
RecipeDifficulty varchar(100) '$.RecipeDifficulty' as difficulty,
RecipeRating varchar(100) '$.RecipeRating' as rating,
RecipeInstructions varchar(100) '$.RecipeInstructions' as instructions,
RecipeName varchar(100) '$.RecipeName' as name,
RecipePrepTime varchar(100) '$.RecipePrepTime' as preptime,
RecipeCookTime varchar(100) '$.RecipeCookTime' as cooktime,
ImageURL varchar(100) '$.ImageURL' as imgurl,
RecipeProtein varchar(100) '$.RecipeProtein' as protien,
RecipeFats varchar(100) '$.RecipeFats' as fats,
RecipeCarbs varchar(100) '$.RecipeCarbs' as carbs,
RecipeFiber varchar(100) '$.RecipeFiber' as fibre,
RecipeDescription varchar(100) '$.RecipeDescription' as reciepdescription,
);
select
quantity,sizename,ingredientname
into #tmprecipeingrident
from OPENJSON(@data,'$.Rootobject.recipeIngredients')
WITH (
IngredientListQuanity varchar(100) '$.IngredientListQuanity' as quantity,
MeasurementSizeName varchar(100) '$.MeasurementSizeName' as sizename,
IngredientName varchar(100) '$.IngredientName' as ingredientname
);
select * from #tmprecipe;
select * from #tmprecipeingrident;
drop table #tmprecipeingrident;
drop table #tmprecipe;
end
但是我不认为(?)我可以轻松地将索引链变成变量并以相同的方式使用它?
a = {"Alice": {"Car": {"Color": "Blue"}}}
a["Alice"]["Car"]["Color"]
>>> "Blue"
列表具有a = {"Alice": {"Car": {"Color": Blue}}}
nested_key = ["Alice"]["Car"]["Color"] # for use in: a[nested_key]
>>> TypeError: list indicies must be integer, not str
对象;但是有没有办法为变量分配“类似键”的对象?
否则,我认为最好的选择是slice()
样式函数(例如https://stackoverflow.com/a/28225660/2588039)?
答案 0 :(得分:0)
您可以创建一个在键上循环的函数,每次在字典上索引索引项,并带有给定的键列表:
def get_nested_value(dct, key_list)
value = dct
for key in key_list:
value = value[key]
return value
keys = ['Alice', 'Car', 'Colour']
print(get_nested_value(a, keys))