Python 将数据上载到json

Python 将数据上载到json,python,json,Python,Json,我有一个按特定扩展名过滤文档的函数,可以执行过滤,但编写json并将其传递到txt文件时存在问题。不带f的json.dump。写作也不起作用。 您也许可以帮助解决这个问题,谢谢 def get_file_json(self): result = [] documents = Document.objects.all() for document in documents: extension = document.source_file.name.spli

我有一个按特定扩展名过滤文档的函数,可以执行过滤,但编写json并将其传递到txt文件时存在问题。不带f的json.dump。写作也不起作用。 您也许可以帮助解决这个问题,谢谢

def get_file_json(self):
    result = []
    documents = Document.objects.all()
    for document in documents:
        extension = document.source_file.name.split('.')[-1]
        print(extension)
        if extension == 'txt' or extension == 'pdf':
            result.append(document.source_file.name)
    if result:
        with open('user_documents.txt', 'w') as f:
            f.write(json.dump(result, f))
        self.stdout.write(self.style.SUCCESS(f'ОК!'))

您当前的代码正在写入文件,然后尝试不向其中写入任何内容,因为这是
json.dump
的返回值

任用

json.dump(result, f)  # Dump result to `f`
或者不如

f.write(json.dumps(result))  # Generate string of result, write to `f`

问题解决了,谢谢大家

    def get_file_json(self, documents, filename):
    result = []
    for document in documents:
        extension_docx = document.source_file.name.split('.')[-1]
        if extension_docx == 'docx':
            result.append({"docx": document.source_file.name, "pdf": self.get_pdf_path(document)})
    if result:
        with open(filename, 'w+') as f:
            f.write(json.dumps(result))

您得到的错误是什么?如果可能,请编辑您的原始帖子,使其包含stack trace errorwrite()参数必须是str而不是none…这是一个错误,但如果您只使用json.dump、json.dumps或f。write(json.dumps(result))不会产生所需的结果,上传到json并保存到txt文件没有理由让普通的
json.dump(result,f)
不能与该代码和Python 3一起工作。您确定要在正确的位置查找该
用户\u documents.txt
?你知道写在哪里吗?(
print(f.name)
会告诉你。)他们在问题中说“没有f.write的json.dump也不起作用”