首页 > 解决方案 > 是否有任何 JSON 标签过滤示例?

问题描述

我有一个 json 文件,我需要列出所有数据的所有“selftext”元素。有什么例子吗?

数据示例

{   "data": [
    {      
        "selftext": "hello there",
        "textex": true,

   },

标签: pythonjson

解决方案


如果您希望能够从任意级别的任意 json 中找到密钥,则应使用递归:

def findkey(data, key, resul = None):
    if resul is None: resul=[]                # initialize an empty list for the results
    if isinstance(data, list):                # walk down into lists
        for d in data:
            findkey(d, key, resul)
    elif isinstance(data, dict):              # dict processing
        for k,v in data.items():
            if (k == key) and isinstance(v, str):    # the expected key and a string value?
                resul.append(v)
            elif isinstance(v, list) or isinstance(v, dict):
                findkey(v, key, resul)        # recurse if value is a list or a dict
    return resul

例子:

>>> data = {   "data": [
    {
        "selftext": "hello there",
        "textex": True,

   },
  ]}
>>> findkey(data, 'selftext')
['hello there']

推荐阅读