使用 python JSON 的 Dropbox 元数据

Dropbox metadata to JSON with python

我正在尝试使用以下方法以 json 格式输出保管箱中某些文件的元数据。

for entry in dbx.files_list_folder(path = '/TG/').entries:
    print(entry.name)
    path = ("/TG/" + str(entry.name))
    data_output = {dbx.files_get_metadata(path=path)}

    if '.py' in path:
        print(data_output)

        with open(write_file, 'w') as outfile:
            json.dump(data_output, outfile)

它正在输出 TypeError: Object of type set is not JSON serializable 然而。

通过使用 {},您将 files_get_metadata 调用的结果放入 set,而不是 JSON 可序列化。您共享的代码中似乎不需要在此处进行设置,因此您可以删除 {}。这将留下实际的 FileMetadata 类型,尽管它实际上也不是 JSON 可序列化的。您需要将其转换为对您的用例有意义的内容。例如,最简单的,只需在其上调用 str

此外,正如所写,您的代码有点多余。 files_list_folder 方法已经为您提供了与 files_get_metadata 相同的信息,因此您可以放弃 files_get_metadata 调用。 files_list_folder 方法 returns 与 files_get_metadata returns 相同的 Metadata 个对象的列表。 (删除 files_get_metadata 调用应该也会使您的代码 运行 更快。)

另外,也可以直接从入口获取路径,无需重构。

经过所有这些更改后,它看起来像:

for entry in dbx.files_list_folder(path = '/TG/').entries:
    print(entry.name)

    if '.py' in entry.path_lower:
        print(entry)

        with open(write_file, 'w') as outfile:
            json.dump(str(entry), outfile)  # or whatever conversion or formatting you want instead of just str