迭代python中的多维json

时间:2017-06-12 18:59:15

标签: json python-2.7 iteration

抱歉发布了错误的格式,希望现在我的查询很清楚。 我正在解析一个JSON,它基本上是我的框架的配置文件。 这是它的样子: My JSON JSON Random Field's values

我的代码:

def makeCombination():
data = schemaConfig["PostData"]
out_json = []
for v1, v2, v3, v4, v5, v6 in product(data['size']['testing_type']['random'], data['start_index']['testing_type']['random'], data['campaign_sub_type']['testing_type']['random'], data['campaign_type']['testing_type']['random'], data['api_key']['testing_type']['random'], data['project_id']['testing_type']['random']):
    out_json.append({'size': v1,'start_index': v2,'campaign_sub_type': v3,'campaign_type': v4,'api_key': v5, 'project_key': v6})
    return out_json


def runRegressionFunc():
randomList = makeCombination()
tempOutList = list()
for comb in randomList:
    tempDoc = dict()
    for funcName in comb:
        (key, val) = callOtherClasses(funcName)
        tempDoc[key] = val
    tempOutList.append(tempDoc)

return tempOutList

我想从"随机"中获得所有可能的组合。 makeCombination()中的所有字段,并将其返回到runRegressionFunc()。

P.S。我是编码世界的新手:)

1 个答案:

答案 0 :(得分:0)

首先,你的json是不正确的。修复语法后,您可以使用itertools.product获取api_keyproject_key内容的所有组合,并使用您想要的信息创建新的dicts列表。

>>> from itertools import product
>>> import pprint
>>>
>>> json_data = {"PostData" : {
... "api_key": {
...   "data_type": "String",
...   "testing_type": {
...     "random": [
...       "veryShortString",
...       "shortString",
...       "longString"
...       ]}},
... 
...  "project_key": {
...   "data_type": "String",
...   "testing_type": {
...     "random": [
...       "veryShortString",
...       "shortString",
...       "longString"
...       ]}}}}
>>>
>>> data = json_data['PostData']
>>> out_json = []
>>> for v1, v2 in product(data['api_key']['testing_type']['random'], data['project_key']['testing_type']['random']):
...      out_json.append({'api_key' : v1, 'project_key' : v2 })
... 
>>>
>>> pprint.pprint(out_json)
[{'api_key': 'veryShortString', 'project_key': 'veryShortString'},
 {'api_key': 'veryShortString', 'project_key': 'shortString'},
 {'api_key': 'veryShortString', 'project_key': 'longString'},
 {'api_key': 'shortString', 'project_key': 'veryShortString'},
 {'api_key': 'shortString', 'project_key': 'shortString'},
 {'api_key': 'shortString', 'project_key': 'longString'},
 {'api_key': 'longString', 'project_key': 'veryShortString'},
 {'api_key': 'longString', 'project_key': 'shortString'},
 {'api_key': 'longString', 'project_key': 'longString'}]