简体   繁体   English

列表理解从 JSON 获取值

[英]List comprehension getting values from JSON

I have this json with different levels:我有不同级别的json:

[{'A': 1, 'B': 2, 'CA': {'CA1': '3', 'CA23': '4'}},
 {'A': 1, 'B': {'CA1': '3'}, 'CA': {'CA1': '3', 'CA23': '4'}}]

And I want to get only the values for each row using list comprehension: The expected result is:我只想使用列表理解获取每一行的值:预期结果是:

[[1, 2, '3', '4'], [1, '3', '3', '4']]

Without using list comprehension this code work:不使用列表理解此代码工作:

values = []

for row in json:
    rows = []
    for item in row.items():
        if str(row[item[0]]).startswith("{"):
            temp = row[item[0]].values()
        else:
            temp = [row[item[0]]]
        rows.extend(temp)

    values.append(rows)

Some ideas?一些想法?

Here's a way to do it that cheats a little by using an auxiliary helper function to flatten the nested dictionary objects comprising each "row" of your data-structure.这是一种通过使用辅助辅助函数来展平构成数据结构的每一“行”的嵌套字典对象的方法。

import json  # For pretty-printing data and results.
from collections.abc import MutableMapping

def flatten(nested):
    ''' Yield values from nested dictionary data structure. '''
    for value in nested.values():
        if isinstance(value, MutableMapping):  # Nested?
            yield from flatten(value)
        else:
            yield value


json_values = [{'A': 1, 'B': 2, 'CA': {'CA1': '3', 'CA23': '4'}},
               {'A': 1, 'B': {'CA1': '3'}, 'CA': {'CA1': '3', 'CA23': '4'}}]

print('Before:')
print(json.dumps(json_values, indent=4))

# Here's the list comprehension.
result = [list(flatten(nested)) for nested in json_values]
print()
print('After:')
print(json.dumps(result, indent=4))

Output:输出:

Before:
[
    {
        "A": 1,
        "B": 2,
        "CA": {
            "CA1": "3",
            "CA23": "4"
        }
    },
    {
        "A": 1,
        "B": {
            "CA1": "3"
        },
        "CA": {
            "CA1": "3",
            "CA23": "4"
        }
    }
]
After:
[
    [
        1,
        2,
        "3",
        "4"
    ],
    [
        1,
        "3",
        "3",
        "4"
    ]
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM