在Python中,如何简明地获取json数据中的嵌套值? [英] In Python, how to concisely get nested values in json data?
问题描述
我从JSON加载了数据,并尝试使用列表作为输入提取任意嵌套值,其中该列表对应于连续子代的名称.我想要一个函数 get_value(data,lookup),该函数通过将 lookup 中的每个条目视为嵌套子项,从数据中返回值.
I have data loaded from JSON and am trying to extract arbitrary nested values using a list as input, where the list corresponds to the names of successive children. I want a function get_value(data,lookup) that returns the value from data by treating each entry in lookup as a nested child.
在下面的示例中,当lookup=['alldata','TimeSeries','rates']
时,返回值应为[1.3241,1.3233]
.
In the example below, when lookup=['alldata','TimeSeries','rates']
, the return value should be [1.3241,1.3233]
.
json_data = {'alldata':{'name':'CAD/USD','TimeSeries':{'dates':['2018-01-01','2018-01-02'],'rates':[1.3241,1.3233]}}}
def get_value(data,lookup):
res = data
for item in lookup:
res = res[item]
return res
lookup = ['alldata','TimeSeries','rates']
get_value(json_data,lookup)
我的示例有效,但是有两个问题:
My example works, but there are two problems:
-
这是低效-在我的 for循环中,我将整个TimeSeries对象复制到 res 中,然后才将其替换为如@Andrej Kesely所述, res 是每次迭代的参考,因此不会复制数据. - 不简洁-我希望能够找到一种简洁的(例如,一两行)使用列表理解语法的方式提取数据的方式
It's inefficient - In my for loop, I copy the whole TimeSeries object to res, only to then replace it with the rates list.As @Andrej Kesely explained, res is a reference at each iteration, so data isn't being copied.- It's not concise - I was hoping to be able to find a concise (eg one or two line) way of extracting the data using something like list comprehension syntax
推荐答案
如果您希望使用单行代码,并且正在使用Python 3.8,则可以使用赋值表达式("walrus operator" ):
If you want one-liner and you are using Python 3.8, you can use assignment expression ("walrus operator"):
json_data = {'alldata':{'name':'CAD/USD','TimeSeries':{'dates':['2018-01-01','2018-01-02'],'rates':[1.3241,1.3233]}}}
def get_value(data,lookup):
return [data:=data[item] for item in lookup][-1]
lookup = ['alldata','TimeSeries','rates']
print( get_value(json_data,lookup) )
打印:
[1.3241, 1.3233]
这篇关于在Python中,如何简明地获取json数据中的嵌套值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!