首页 > 解决方案 > 使用 flatten_json 库减少 api 字典中的输入量

问题描述

我在使用 API 的 python 中执行 ETL,可以返回并使用函数 flateen,但通过创建更多级别生成了许多列(超过 900 个),所以我想将其限制为最多三个级别。

我从库中的以下存储库中测试了一些命令,但没有成功。

https://github.com/amirziai/flatten

dict_flattened = (flatten(record, '.') for record in row)

我测试了这个,但它产生了附加的错误。 错误

 response = requests.post(url, json=body, headers=headers)
#response = requests.get(url, headers=headers)
if (200 == response.status_code):
    result = json.loads(response.text)niveis = flatten(
    result,
    separator=".",
    root_keys_to_ignore=None,
    replace_separators=None):
"""
Flattens a dictionary with nested structure to a dictionary with no
hierarchy
Consider ignoring keys that you are not interested in to prevent
unnecessary processing
This is specially true for very deep objects
:param nested_dict: dictionary we want to flatten
:param separator: string to separate dictionary keys by
:param root_keys_to_ignore: set of root keys to ignore from flattening
:param str replace_separators: Replace separators within keys
:return: flattened dictionary
"""
assert isinstance(result, dict), "flatten requires a dictionary input"
assert isinstance(separator, six.string_types), "separator must be string"

if root_keys_to_ignore is None:
    root_keys_to_ignore = set()

if len(result) == 0:
    return {}

# This global dictionary stores the flattened keys and values and is
# ultimately returned
flattened_dict = dict()

标签: pythonarraysjsonflatten

解决方案


推荐阅读