Langchain JSON loader (windows 环境下)

由于windows下无法安装jq,需要自己写JSON Loader。这里提供我的代码~
使用的时候需要自行根据自己的需要修改哦,重点是需要学习的部分要放在page_content 里,并且类型为str

import json
from pathlib import Path
from typing import List, Optional, Union

from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader


class JSONLoader(BaseLoader):
    def __init__(
            self,
            file_path: Union[str, Path]
    ):
        self.file_path = Path(file_path).resolve()

    def create_documents(self, data):
        documents = []
        for item in data:
            item_str = json.dumps(item, ensure_ascii=False)
            document = Document(page_content=item_str, metadata={})
            documents.append(document)
        return documents

    def load(self) -> List[Document]:
        """Load and return documents from the JSON file."""

        docs = []
        with open(self.file_path, mode="r", encoding="utf-8") as json_file:
            try:
                data = json.load(json_file)
                docs = self.create_documents(data)
            except json.JSONDecodeError:
                print("Error: Invalid JSON format in the file.")
        return docs


file_path = 'csvjson.json'
json_loader = JSONLoader(file_path)
docs = json_loader.load()
print(docs)

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值