[英]Building Command From Variable Number of Args Passed
我的方法接受兩個屬性和一個json
列表,並返回相應的值。 它按預期工作。
現在,我想添加功能以使其返回相應的值,而不管其深度如何。
例如,現在它接受parent
和child
args並返回一個值(請參見下文): return jsonprops[parent][child]
。
是否可以使其接受任意數量的args並返回相應的值? return jsonprops[parent][child1][child2]....[childN]
嗎?
我已經找到了將可變數量的args
傳遞給方法的示例(如下),但是我不確定如何構造return jsonprops[parent][child]
因為它必須在[]
對args進行排序。
所需的解決方案將返回return jsonprops[parent][child]
以及return jsonprops[parent][child1][child2][child3][child4]
將可變數量的args傳遞給方法:
def multipleArgs(*arg):
print "Called with", len(arg), "arguments:", arg
讀取json文件:
import json
def read_json(parent, child, jsonprops=[])
return jsonprops[parent][child]
exampleFile = json.loads(open(example.json).read())
childInfo = read_json('parentProps', 'childProp1', exampleFile)
print childInfo
示例json
{
"generalInfo": {
"name": "example",
"schemaVersion": "1.0",
"description": "metadata to be an example"
},
"parentProps": {
"childProp1": "hi 1",
"childProp2": "hi 2",
"childProp3": {
"newParent": [
{
"parent1": [
{
"grandChild1": "GC1",
"grandChild2": "GC2",
"grandChild3": "GC3"
},
{
"numberofKids": "5",
"grandChild4": "GC4",
"grandChild5": "GC5",
"grandChild6": "GC6"
}
],
"parent2": [
{
"numberofKids": "1",
"grandChild11": "GC11",
"grandChild12": "GC12",
"grandChild13": "GC13"
},
{
"grandChild14": "GC14",
"grandChild15": "GC15",
"grandChild16": "GC16"
}
]
}
]
}
}
}
如何將jsonpath與objectpath模塊一起使用:
In [22]: from objectpath import Tree
In [23]: j = """
...: {
...: "generalInfo": {
...: "name": "example",
...: "schemaVersion": "1.0",
...: "description": "metadata to be an example"
...: },
...: "parentProps": {
...: "childProp1": "hi 1",
...: "childProp2": "hi 2",
...: "childProp3": {
...: "newParent": [
...: {
...: "grandChild1": "GC1",
...: "grandChild2": "GC2",
...: "grandChild3": "GC3"
...: },
...: {
...: "grandChild4": "GC4",
...: "grandChild5": "GC5",
...: "grandChild6": "GC6"
...: }
...: ]
...: }
...: }
...: }"""
In [24]: j = json.loads(j)
In [25]: next(Tree(j).execute('$..{}..{}'.format('parentProps', 'childProp1')))
Out[25]: 'hi 1'
In [53]: next(Tree(j).execute('$..{}..{}'.format('newParent', 'grandChild5')))
Out[53]: 'GC5'
然后,您的函數將加載json並借助objectpath返回結果(如果有)
要從數據結構內的任意深度訪問值,您可能要使用循環。 這是一種簡單的方法:
def get_value(data, *keys):
for key in keys:
data = data[key]
return data
您還可以使用由reduce
函數執行的隱式循環(在Python 3中是functools
模塊的一部分):
from functools import reduce # this line is only needed in Python 3
from operator import getitem
def get_value(*args): # data should be first argument, followed by any number of keys
return reduce(getitem, args)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.