Python。如何从 JSON 获取目录路径?

标签 python json parsing

我正在从 API 接收 json 格式的答案:

    "files":[
    {
      "name":"main",
      "node_type":"directory",
      "files":[
        {
          "name":"source1",
          "node_type":"directory",
          "files":[
            {
              "name":"letters",
              "node_type":"directory",
              "files":[
                {
                  "name":"messages.po",
                  "node_type":"file",
                  "created":"2014-08-14 08:51:41",
                  "last_updated":"2014-08-14 08:51:42",
                  "last_accessed":"0000-00-00 00:00:00"
                }
              ]
            }
          ]
        },
        {
          "name":"source2",
          "node_type":"directory",
          "files":[

          ]
        }
      ]
    },
    {
      "name":"New Directory",
      "node_type":"directory",
      "files":[
        {
          "name":"prefs.js",
          "node_type":"file",
          "created":"2014-08-14 08:11:53",
          "last_updated":"2014-08-14 08:11:53",
          "last_accessed":"0000-00-00 00:00:00"
        }
      ]
    },
    {
      "name":"111",
      "node_type":"directory",
      "files":[
        {
          "name":"222",
          "node_type":"directory",
          "files":[
            {
              "name":"333",
              "node_type":"directory",
              "files":[
                {
                  "name":"cli.mo",
                  "node_type":"file",
                  "created":"2014-08-14 08:51:30",
                  "last_updated":"2014-08-14 08:51:30",
                  "last_accessed":"0000-00-00 00:00:00"
                }
              ]
            }
          ]
        }
      ]
    }
  ],

项目结构是:

├──111──222──333───cli.mo
├──main──source1──letters───messages.po
         └──source2
├──New Directory──prefs.js

如何解析 json,这样我就可以收到这样的返回:

/111/222/333/cli.mo
/main/source1/letters/messages.po
/main/source2/
/New Directory/prefs.js

我尝试用 Python 编写一些代码,但我是初学者,我的尝试失败了。

最佳答案

如果您希望实际接收回字符串,我建议使用生成器:

def parse(data, parent=''):
    if data is None or not len(data):
        yield parent
    else:
        for node in data:
            for result in parse(
                    node.get('files'), parent + '/' + node.get('name')):
                yield result

您还可以在 yield Parent 语句上使用变体,让 /main/source2 返回时带有尾部斜杠 (/main/source2/),尽管我发现它太冗长了:

        yield parent + ('/' if data is not None and not len(data) else '')

将您的 JSON 解析列表传递给上面的 parse 函数,您将收到一个迭代器,该迭代器将为您提供它在数据中找到的字符串:

import json

# shamelessly ignoring PEP8 for the sake of space
data = '''
[{"files": [{"files": [{"files": [{"node_type": "file", "last_accessed": "0000-00-00 00:00:00", "last_updated": "2014-08-14 08:51:42",
"name": "messages.po", "created": "2014-08-14 08:51:41"}], "node_type": "directory", "name": "letters"}], "node_type": "directory",
"name": "source1"}, {"files": [], "node_type": "directory", "name": "source2"}], "node_type": "directory", "name": "main"}, {"files":
[{"node_type": "file", "last_accessed": "0000-00-00 00:00:00", "last_updated": "2014-08-14 08:11:53", "name": "prefs.js", "created":
"2014-08-14 08:11:53"}], "node_type": "directory", "name": "New Directory"}, {"files": [{"files": [{"files": [{"node_type": "file",
"last_accessed": "0000-00-00 00:00:00", "last_updated": "2014-08-14 08:51:30", "name": "cli.mo", "created": "2014-08-14 08:51:30"}],
"node_type": "directory", "name": "333"}], "node_type": "directory", "name": "222"}], "node_type": "directory", "name": "111"}]
'''

for item in parse(json.loads(data)):
    print item

运行上面的命令会给你

/main/source1/letters/messages.po
/main/source2
/New Directory/prefs.js
/111/222/333/cli.mo

作为输出。这里有一篇关于生成器的非常有趣的读物:What does the "yield" keyword do in Python? - 我建议仔细阅读所有答案。

关于Python。如何从 JSON 获取目录路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25318791/

相关文章:

c# - 从字符串中提取日期值

python - 使用字典替换文本文件中的单词

python - 将二进制值的文本转换为 numpy 文件

html - 样式化 JSON 页面

javascript - 访问多维对象 JavaScript

java - Antlr4 子上下文索引

python - 检查 websocket 客户端的 URL - python

python - 调用 setup.py test 命令时如何告诉 pbr 使用 pytest?

java - 从我的 ListView 中添加 ItemOnClick,使用 JSON 从 MYSQL 中获取数据

python - 选择字符串中的日期